【发布时间】:2014-09-12 16:31:30
【问题描述】:
如何循环获取Pythoniterator的当前项的索引?
例如,当使用返回迭代器的正则表达式finditer函数时,如何在循环中访问迭代器的索引。
for item in re.finditer(pattern, text):
# How to obtain the index of the "item"
【问题讨论】:
如何循环获取Pythoniterator的当前项的索引?
例如,当使用返回迭代器的正则表达式finditer函数时,如何在循环中访问迭代器的索引。
for item in re.finditer(pattern, text):
# How to obtain the index of the "item"
【问题讨论】:
迭代器不是为索引而设计的(请记住,它们是懒惰地生成它们的项目)。
相反,您可以使用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
>>>
【讨论】: