需要在python中的迭代器的开头添加一个元素 [英] Need to add an element at the start of an iterator in python
问题描述
我有一个程序如下:
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()*
如何在迭代器的开头添加元素?
(或者有更简单的方法吗?)
How do I add an element to the start of the iterator? (Or is there an easier way to do this?)
编辑:好的,让我这样说吧。我需要迭代器中的下一个元素而不删除它。
我该怎么做>?
OK let me put it this way. I need the next element in an iterator without removing it. How do I do this>?
推荐答案
Python迭代器本身功能非常有限 - 没有附加或类似的东西。您需要将通用迭代器包装在添加该功能的包装器中。例如:
Python iterators, as such, have very limited functionality -- no "appending" or anything like that. You'll need to wrap the generic iterator in a wrapper adding that functionality. E.g.:
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)
这是Python 2.5(也应该在2.6中工作) - 建议2.6和必须为3.any(使用 next(self.it)
而不是 self.it.next()
并定义 __ next __
而不是 next
)。
This is Python 2.5 (should work in 2.6 too) -- slight variants advised for 2.6 and mandatory for 3.any (use next(self.it)
instead of self.it.next()
and define __next__
instead of next
).
编辑:OP现在说他们需要的是在没有消费的情况下向前看。包装仍然是最佳选择,但另一种选择是:
Edit: the OP now says what they need is "peek ahead without consuming". Wrapping is still the best option, but an alternative is:
import itertools
...
o, peek = itertools.tee(o)
if isneat(peek.next()): ...
这不会提前 o
(如果您决定要这样做,请记得提前; - )。
this doesn't advance o
(remember to advance it if and when you decide you DO want to;-).
这篇关于需要在python中的迭代器的开头添加一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!