问题
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)
回答1:
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:
Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. [...] This means that we can write
for k in dict: ...
which is equivalent to, but much faster than
for k in dict.keys(): ...
as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.
Add methods to dictionaries that return different kinds of iterators explicitly:
for key in dict.iterkeys(): ... for value in dict.itervalues(): ... for key, value in dict.iteritems(): ...
This means that
for x in dict
is shorthand forfor x in dict.iterkeys()
.
回答2:
This "missing link" between your first and second code snippet explains why they are equivalent:
print "-"*10
for test in states.items():
state, abbrev = test
print "%s has the city %s" % (state, abbrev)
来源:https://stackoverflow.com/questions/35968877/learn-python-the-hard-way-exercise-39