如何在循环中获取当前迭代器项的索引?

时间:2014-07-22 01:23:36

标签: python iterator

如何在循环中获取Python iterator的当前项的索引?

例如,当使用返回迭代器的正则表达式finditer函数时,如何在循环中访问迭代器的索引。

for item in re.finditer(pattern, text):
    # How to obtain the index of the "item"

1 个答案:

答案 0 :(得分:21)

迭代器不是设计为索引的(请记住它们懒洋洋地生成它们的项目)。

相反,您可以使用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
>>>