【问题标题】:How to get the item currently pointed at by iterator without incrementing?如何获取迭代器当前指向的项目而不增加?
【发布时间】:2012-07-03 00:01:27
【问题描述】:

有没有办法在不增加迭代器本身的情况下获取 Python 中迭代器指向的项目?例如,我将如何使用迭代器实现以下内容:

looking_for = iter(when_to_change_the_mode)
for l in listA:
    do_something(looking_for.current())
    if l == looking_for.current():
        next(looking_for)

【问题讨论】:

    标签: python iterator


    【解决方案1】:

    迭代器无法获取当前值。如果您愿意,请自己保留对它的引用,或者包装您的迭代器为您保留它。

    【讨论】:

      【解决方案2】:
      looking_for = iter(when_to_change_the_mode)
      current = next(looking_for)
      for l in listA:
          do_something(current)
          if l == current:
              current = next(looking_for)
      

      问题: 如果在迭代器的末尾怎么办? next 函数允许使用默认参数。

      【讨论】:

      • @glglgl 谢谢我会改的。
      • 如何检查是否有下一次迭代?
      【解决方案3】:

      我认为没有内置方法。只需将有问题的迭代器包装在缓冲一个元素的自定义迭代器中就很容易了。

      例如:How to look ahead one element in a Python generator?

      【讨论】:

        【解决方案4】:

        当我需要这样做时,我通过创建如下类来解决它:

        class Iterator:
            def __init__(self, iterator):
                self.iterator = iterator
                self.current = None
            def __next__(self):
                try:
                    self.current = next(self.iterator)
                except StopIteration:
                    self.current = None
                finally:
                    return self.current
        

        这样您就可以像使用标准迭代器一样使用 next(itr),并且可以通过调用 itr.current 来获取当前值。

        【讨论】:

          猜你喜欢
          • 2022-11-20
          • 2016-01-02
          • 2021-05-04
          • 2011-05-06
          • 1970-01-01
          • 1970-01-01
          • 2019-12-01
          • 2016-07-01
          • 1970-01-01
          相关资源
          最近更新 更多