【发布时间】:2016-06-28 09:21:21
【问题描述】:
在 Learn Python The Hard Way 的练习 39 中,第 37 到 39 行如下所示:
print "-"*10
for state, abbrev in states.items():
print "%s has the city %s" % (state, abbrev)
我以为我明白这一点。我以为 Python 是从“states”中获取 KEY:VALUE 并将 KEY 分配给“state”,将 VALUE 分配给“abbrev”。
但是,当我输入以下代码时,我发现发生了一些奇怪的事情:
print "-"*10
for test in states.items():
print "%s has the city %s" % (test)
它产生与原始代码相同的输出。
但是,它只有在您将%s 两次放入 print 语句时才有效。
有人能解释一下“测试”发生了什么吗?
究竟什么是“测试”?它是一个元组吗?
它似乎包含来自states.items() 的KEY 和VALUE。
我在这里查看了练习 39 中的其他一些问题,但没有找到相同的查询。
代码如下(适用于 Python 2.7)
# create a mapping of state to abbreviation
states = {
'Oregan': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York' : 'NY',
'Michigan' : 'MI'
}
print "-"*10
for state, abbrev in states.items():
print "%s has the city %s" % (state, abbrev)
print "-"*10
for test in states.items():
print "%s has the city %s" % (test)
【问题讨论】:
-
你不必使用 states.items(),字典的默认可迭代是 key
标签: python python-2.7 dictionary tuples enumeration