发布时间:2019-08-28 09:14:06编辑:auto阅读(1949)
python的for如何获得当前循环次数?
摘自:http://markmail.org/message/ryfven2i75kgsrsm
enumerate是python 2.3中新增的内置函数,它的英文说明为:
enumerate( iterable)
Return an enumerate object. iterable must be a sequence, an iterator,or some other object which supports iteration. The next() method ofthe iterator returned by enumerate() returns a tuple containing acount (from zero) and the corresponding value obtained from iteratingover iterable. enumerate() is useful for obtaining an indexed series:(0, seq[0]), (1, seq[1]), (2, seq[2]), .... New in version 2.3.它特别适合用于一个for循环时,当我们同时需要计数和元素时可以使用这个函数。举个简单的例子,有一个字符串数组,需要一行一行打印出来,同时每行前面加上计数,从1开始。
s = ['abc', 'This is a test', 'Hello, Python']
for i, line in enumerate(s):
print i+1, line
上一篇: 【Python】提取网页正文内容的相关模
下一篇: 在Python中定义和使用 抽象类及抽象
48867
47938
38713
35861
30286
27039
26072
20906
20705
19068
504°
599°
610°
611°
588°
573°
641°
714°
832°
932°