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