2015-04-04 63 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