从迭代器中删除N个值的Pythonic解决方案 [英] Pythonic solution to drop N values from an iterator
本文介绍了从迭代器中删除N个值的Pythonic解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否存在从迭代器中删除n
值的pythonic解决方案?您可以通过如下方式丢弃n
值来做到这一点:
Is there a pythonic solution to drop n
values from an iterator? You can do this by just discarding n
values as follows:
def _drop(it, n):
for _ in xrange(n):
it.next()
但这是IMO,不如Python代码那么优雅.我在这里缺少更好的方法吗?
But this is IMO not as elegant as Python code should be. Is there a better approach I am missing here?
推荐答案
我相信您正在寻找食用"食谱
I believe you are looking for the "consume" recipe
http://docs.python.org/library/itertools.html#recipes >
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(islice(iterator, n, n), None)
如果n
为None
时不需要特殊行为,
您可以使用
If you don't need the special behaviour when n
is None
,
you can just use
next(islice(iterator, n, n), None)
这篇关于从迭代器中删除N个值的Pythonic解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文