什么是pythonic方法来实现一个迭代器,它排除最后一个元素,而不知道它的长度?
一个例子:
>>> list(one_behind(iter(range(10)))
... [0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> iter_ = one_behind(iter((3, 2, 1)))
>>> next(iter_)
... 3
>>> next(iter_)
... 2
>>> next(iter_)
... StopIteration
一个简单的方法是使用一个循环并存储前一个值,但我想要一些更短的东西。
使用循环的参考实现:
def one_behind(iter_):
prev = None
for i, x in enumerate(iter_):
if i > 0:
yield prev
prev = x
答案 0 :(得分:4)
import itertools
def behind(it):
# it = iter(it) # to handle non-iterator iterable.
i1, i2 = itertools.tee(it)
next(i1)
return (next(i2) for x in i1)
用法:
>>> list(behind(iter(range(3))))
[0, 1]
答案 1 :(得分:2)
比参考函数简单:
def lag(iter):
previous_item = next(iter)
for item in iter:
yield previous_item
previous_item = item
答案 2 :(得分:0)
def one_behind(iter):
q = collections.deque()
q.append(next(iter))
while True:
q.append(next(iter))
yield q.popleft()
>>> iterator = iter(range(4))
>>> list(one_behind(iterator))
[0, 1, 2]