在需要遍历数列时,通常做法为:
for i in range (0 , len (list )): print i , list [ i ]
而enumerate函数则可以优雅的解决此类问题,首先看下它的定义:
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