在須要遍歷數列時,一般作法爲:python
for i in range (0 , len (list )): print i , list [ i ]
而enumerate函數則能夠優雅的解決此類問題,首先看下它的定義:
ide
def enumerate (collection ): 'Generates an indexed series: (0,coll[0]), (1,coll[1]) ...' i = 0 it = iter (collection ) while 1 : yield (i , it . next ()) i += 1
用法:
函數
for index , text in enumerate (list )): print index , text