So many collections can be iterated, like ordered collections: list
, tuple
, str
, and unicode
; unordered collections: set
and dict
Iteration with index
enumerate()
, this method can bind index
and name
at the same time, each element is not the one which existed, after binding the index, it will become a tuple which contains index and name
example
List: L = ['Bin', 100, True]
enumerate(L) = [(0, 'Bin'), (1, 100), (2, True)]
//Code==========
for index, name in enumerate(L):
print index, '-', name
//Result==========
0 - Bin
1 - 100
2 - True
By using
zip()
we can easily inplement theenumerate()
,
numList
=range(3)
=>[0, 1, 2]
zip( numList , ['Bin', 100, True] )
=>[(0, 'Bin'), (1, 100), (2, True)]
Iteration of dict
========== Python3 ==========
dict.items()
: return a list of entities, each entity is a tuple which contains a key and a value
dict.keys()
: return a list of keys
dict.values()
: return a list of values
example
//Code==========
dict = {'Name': 'Bin', 'Age': 3}
for i,j in dict.items():
print(i, ":", j)
//Result==========
Name : Bin
Age : 3
========== Python2 ==========
dict.values()
: return a list of values
dict.itervalues()
: extracting value from dict in each iteration step [retired in python3]
dict.items()
: return a list of entities
dict.iteritems()
: extracting a pair of key and value from dict in each iteration step [retired in python3]
example
//Code==========
d = { 'Joanna': 100, 'Lisa': 85, 'Bart': 59, 'Paul': 74 }
sum = 0.0
for s in d.itervalues():
sum += s
print sum/len(d)
//Result==========
79.5
Forget about those methods which have prefix of
iter