需要在python中的迭代器的开头添加一个元素

Gou*_*ham 3 python iterator

我有一个程序如下:

a=reader.next()
if *some condition holds*:
    #Do some processing and continue the iteration
else:
    #Append the variable a back to the iterator
    #That is nullify the operation *a=reader.next()*
Run Code Online (Sandbox Code Playgroud)

如何在迭代器的开头添加元素?(或者有更简单的方法吗?)

编辑:好的,让我这样说吧.我需要迭代器中的下一个元素而不删除它.我该怎么做>?

kol*_*pto 27

您正在寻找itertools.chain

import itertools

values = iter([1,2,3])  # the iterator
value = 0  # the value to prepend to the iterator

together = itertools.chain([value], values)  # there it is

list(together)
# -> [0, 1, 2, 3]
Run Code Online (Sandbox Code Playgroud)


Ale*_*lli 12

因此,Python迭代器的功能非常有限 - 没有"附加"或类似的东西.您需要将通用迭代器包装在添加该功能的包装器中.例如:

class Wrapper(object):
  def __init__(self, it):
    self.it = it
    self.pushedback = []
  def __iter__(self):
    return self
  def next(self):
    if self.pushedback:
      return self.pushedback.pop()
    else:
      return self.it.next()
  def pushback(self, val):
    self.pushedback.append(val)
Run Code Online (Sandbox Code Playgroud)

这是Python 2.5(也应该在2.6中工作) - 建议2.6的轻微变体和3.any的强制变量(使用next(self.it)而不是self.it.next()和定义__next__而不是next).

编辑:OP现在说他们需要的是"在没有消费的情况下向前看".包装仍然是最好的选择,但另一种选择是:

import itertools
   ...
o, peek = itertools.tee(o)
if isneat(peek.next()): ...
Run Code Online (Sandbox Code Playgroud)

这不会提前o(记得在你决定要做的时候推进它;-).

  • 不用担心 - 迭代器在包装器的情况下通过引用保存,而itertools.tee将消耗额外的空间O(K),其中K是您需要向前查看的项目数.所以"大型迭代器"没问题! (2认同)