Iteration

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 the enumerate(),
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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容