如何获取Python当前项的索引iterator https://docs.python.org/3.7/glossary.html#term-iterator在循环中?
例如当使用正则表达式时finditer
返回迭代器的函数,如何在循环中访问迭代器的索引。
for item in re.finditer(pattern, text):
# How to obtain the index of the "item"
迭代器并不是为索引而设计的(请记住,它们是延迟生成项目的)。
相反,您可以使用enumerate https://docs.python.org/3/library/functions.html#enumerate在生产时对物品进行编号:
for index, match in enumerate(it):
下面是一个演示:
>>> it = (x for x in range(10, 20))
>>> for index, item in enumerate(it):
... print(index, item)
...
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
>>>
请注意,您还可以指定一个数字来开始计数:
>>> it = (x for x in range(10, 20))
>>> for index, item in enumerate(it, 1): # Start counting at 1 instead of 0
... print(index, item)
...
1 10
2 11
3 12
4 13
5 14
6 15
7 16
8 17
9 18
10 19
>>>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)