如何在循环中获取当前迭代器项的索引? [英] How to get the index of the current iterator item in a loop?

查看:170
本文介绍了如何在循环中获取当前迭代器项的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to obtain the index of the current item of a Python iterator in a loop?

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

For example when using regular expression finditer function which returns an iterator, how you can access the index of the iterator in a loop.

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

推荐答案

迭代器的设计目的不是要对其建立索引(请记住,它们会延迟生成其项).

Iterators were not designed to be indexed (remember that they produce their items lazily).

相反,您可以使用 enumerate 对产生的项目进行编号:

Instead, you can use enumerate to number the items as they are produced:

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
>>>

请注意,您还可以指定一个数字来开始计数:

Note that you can also specify a number to start the counting at:

>>> 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
>>>

这篇关于如何在循环中获取当前迭代器项的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆