Python中除迭代器的最后N个元素外的所有元素 [英] All but the last N elements of iterator in Python
本文介绍了Python中除迭代器的最后N个元素外的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中获取除迭代器的最后N个元素之外的所有元素的最佳方法是什么?这是理论上的例子:
What is the best way to get all but the last N elements of an iterator in Python? Here is an example of it in theoretical action:
>>> list(all_but_the_last_n(range(10), 0))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(all_but_the_last_n(range(10), 2))
[0, 1, 2, 3, 4, 5, 6, 7]
推荐答案
仅出于乐趣,这是Ignacio解决方案的一种变体,不需要双端队列.
Just for the fun of it, here's a variation on Ignacio's solution that doesn't require a deque.
>>> def truncate(it, n):
... cache = [next(it) for i in range(n)]
... index = 0
... for val in it:
... val, cache[index] = cache[index], val
... index = (index + 1) % n
... yield val
当我写上面的文章时,我并不特别关心速度...但是也许这会更快一点:
I wasn't especially concerned with speed when I wrote the above... but perhaps this would be a tad faster:
def truncate(it, n):
cache = [next(it) for i in range(n)]
index = 0
for val in it:
yield cache[index]
cache[index] = val
index = (index + 1) % n
这篇关于Python中除迭代器的最后N个元素外的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文