如何在循环中获取Python 迭代器的当前项的索引?
例如,当使用finditer返回迭代器的正则表达式函数时,如何在循环中访问迭代器的索引.
for item in re.finditer(pattern, text):
# How to obtain the index of the "item"
Run Code Online (Sandbox Code Playgroud)
iCo*_*dez 23
迭代器的设计并不是为了编制索引(请记住,它们会懒散地生成它们的项目).
相反,您可以使用enumerate它们生成的项目编号:
for index, match in enumerate(it):
Run Code Online (Sandbox Code Playgroud)
以下是演示:
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)
请注意,您还可以指定一个数字来开始计数:
>>> 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
>>>
Run Code Online (Sandbox Code Playgroud)