问题描述
在学习Python困难之路"练习39中,第37至39行如下所示:
print "-"*10
for state, abbrev in states.items():
print "%s has the city %s" % (state, abbrev)
我以为我明白这一点.我以为Python是从状态"中获取KEY:VALUE并将KEY分配给"state",而将VALUE分配给"abbrev".
但是,当我输入以下代码时,我发现了一件奇怪的事情:
print "-"*10
for test in states.items():
print "%s has the city %s" % (test)
它产生与原始代码相同的输出.但是,只有将%s
放入打印语句两次后,它才能起作用.
有人可以解释测试"发生了什么吗?测试"到底是什么?是元组吗?它似乎同时包含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
是字典,因此当您调用for test in states.items()
时,它将字典的每个项目(a tuple
)分配给test
. /p>
然后,您就像在for state, abbrev in states.items():
>>> for state in states.items():
print (state) # print all the tuples
('California', 'CA')
('Oregan', 'OR')
('Florida', 'FL')
('Michigan', 'MI')
('New York', 'NY')
所有详细信息均可在线获得,例如在 PEP 234-迭代器字典迭代器下的a>:
On Exercise 39 of Learn Python The Hard Way, lines 37 to 39 look like this:
print "-"*10
for state, abbrev in states.items():
print "%s has the city %s" % (state, abbrev)
I thought I understood this. I thought Python was taking the KEY:VALUE from "states" and assigning the KEY to "state" and the VALUE to "abbrev".
However, I found something strange happened when I entered the following code:
print "-"*10
for test in states.items():
print "%s has the city %s" % (test)
It produces the same output as the original code.But, it only works if you put the %s
into the print statement twice.
Can someone explain what is happening with "test"?What exactly is "test"? Is it a Tuple?It seems to contain both the KEY
and the VALUE
from states.items()
.
I have looked through some of the other questions on Exercise 39 here and I haven't found the same query.
The code is listed below (for 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
is a dictionary, so when you called for test in states.items()
it assigns each item of the dictionary (a tuple
) to test
.
Then you are just iterating over the items and printing their keys and values as you would with for state, abbrev in states.items():
>>> for state in states.items():
print (state) # print all the tuples
('California', 'CA')
('Oregan', 'OR')
('Florida', 'FL')
('Michigan', 'MI')
('New York', 'NY')
All the details are available online, for instance in PEP 234 -- Iterators under Dictionary Iterators:
这篇关于艰难地学习Python-练习39的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!