为python构建的迭代计数器
问题描述:
我想迭代一个列表并引用我所在的迭代编号。我可以用一个简单的计数器做到这一点,但是有没有内置函数呢?为python构建的迭代计数器
List= list(range(0,6))
count = 0
for item in List:
print "This is interation ", str(count)
count += 1
答
它是什么那enumerate
是为了!
返回一个枚举对象。序列必须是序列,迭代器或支持迭代的其他对象。
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
而且在迭代,你可以这样做:
for index,element in enumerate(seasons):
#do stuff