如何获取迭代器对象的索引? [英] How to get the index of the iterator object?

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

问题描述

如何访问 iterator Python中的对象?

How to access the index of the current item in the iterator object in Python?

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

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

re.finditer(pattern, text)


推荐答案

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

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

相反,您可以使用 枚举 对产品编号进行编号:

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天全站免登陆