我想遍历一个列表并引用我所在的迭代次数。我可以用一个简单的计数器来完成,但有内置的函数吗?
List= list(range(0,6))
count = 0
for item in List:
print "This is interation ", str(count)
count += 1
这就是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
您应该使用内置函数enumerate
。