Python中enumerate函数用法详解

enumerate函数用于遍历序列中的元素以及它们的下标,多用于在for循环中获得计数,enumerate参数为可遍历的变量,如 字符串,列表等数组

通常状况下对一个列表或数组既要遍历索引又要遍历元素时,会这样写:函数

for i in range (0,len(list)): print i ,list[i] 可是这种方法有些累赘,使用内置enumerrate函数会有更加直接,优美的作法,先看看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字符串

enumerate会将数组或列表组成一个索引序列。使咱们再获取索引和索引内容的时候更加方便以下:it

for index,text in enumerate(list)): print index ,textio

相关文章
相关标签/搜索