【发布时间】:2019-03-06 21:45:05
【问题描述】:
我今天在 Python 中遇到了一个非常奇怪的关于字符串和字典的东西。有人可以向我解释为什么 print 语句在第一个 for 循环中有效,但在第二个 for 循环中失败?
test = 'ab'
test_dict = {}
test_dict[test] = 1
for x, y in test_dict:
print('%s %s' % (x,y))
for x,y in test:
print('%s %s' % (x,y))
【问题讨论】:
-
什么是完整的回溯?
-
第一个打印语句打印出:“a b” 第二个打印语句是错误的,正如预期的那样。
-
你认为 y 在字符串大小写中应该打印什么?
-
test是字符串变量而不是字典 -
"字典是键值对的集合。在这种情况下,x,y 持有 x 中的键和 y 中的值" 不正确,请参阅前面的评论。
标签: python string dictionary iterable-unpacking