1. Using the Enumerate function
L = [‘Adam‘, ‘Lisa‘, ‘Bart‘, ‘Paul‘]
for index, name in enumerate(L):
print index + 1, ‘-‘, name.lower()
2. Using the Zip function
-
for index  NAME  in zip ( range ( 1 Span class= "pun", len ( l 1 l
print index, ‘-‘, name
3. dict element Iteration Access
d = {
‘Adam‘: 95,
‘Lisa‘: 85,
‘Bart‘: 59
}
for (key, value) in d.items():
print("%s: %s" % (key, value))
for key in d:
print("%s: %s" % (key, d[key]))
for key, value in zip(d.keys(), d.values()):
print("%s: %s" % (key, value))
If you read the Python document carefully, you can also find that dict in addition to
values ()method, there is also a
itervalues ()method, with
itervalues ()method Overrides
values ()method, the iteration effect is exactly the same.
for key, value in zip(d.iterkeys(), d.itervalues()):
print("%s: %s" % (key, value))
What is the difference between the two methods?
1. The values () method actually converts a dict to a list containing value.
2. However, the itervalues () method does not convert, and it takes value from dict in sequence during the iteration, so the Itervalues () method saves the memory needed to generate the list, compared to the values () method.
3. Print itervalues () find it returns a <dictionary-valueiterator> object, which shows that in Python, thefor loop can be used to iterate beyond list,tuple,str. Unicode,dict, and so on , any iterator object can be used for a for loop, and the inner iteration of how we usually don't care.
From for notes (Wiz)
Python Index iterations