2015-04-04 43 views
0

我想迭代一個列表並引用我所在的迭代編號。我可以用一個簡單的計數器做到這一點,但是有沒有內置函數呢?爲python構建的迭代計數器

List= list(range(0,6)) 
count = 0 
for item in List: 
    print "This is interation ", str(count) 
    count += 1 

回答

4

它是什麼那enumerate是爲了!

enumerate(sequence, start=0)

返回一個枚舉對象。序列必須是序列,迭代器或支持迭代的其他對象。

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] 
>>> list(enumerate(seasons)) 
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] 

而且在迭代,你可以這樣做:

for index,element in enumerate(seasons): 
    #do stuff