【问题标题】:How to get the index of the current iterator item in a loop? [duplicate]如何在循环中获取当前迭代器项的索引? [复制]
【发布时间】:2014-09-12 16:31:30
【问题描述】:

如何循环获取Pythoniterator的当前项的索引?

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

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

【问题讨论】:

    标签: python iterator


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-03-20
      • 1970-01-01
      • 2012-06-21
      • 2014-01-24
      • 2011-11-18
      • 2022-11-20
      • 2016-08-21
      • 2017-01-24
      • 2010-11-29
      相关资源
      最近更新 更多