Pythonic解决方案从迭代器​​中删除N值

sch*_*mar 6 python iterator

是否存在n从迭代器中删除值的pythonic解决方案?您可以通过丢弃n值来执行此操作,如下所示:

def _drop(it, n):
    for _ in xrange(n):
        it.next()
Run Code Online (Sandbox Code Playgroud)

但是,IMO并不像Python代码那样优雅.我在这里错过了更好的方法吗?

Joh*_*ooy 8

我相信你正在寻找"消费"食谱

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)
Run Code Online (Sandbox Code Playgroud)

如果您在不需要特殊的行为nNone,你可以只使用

next(islice(iterator, n, n), None)
Run Code Online (Sandbox Code Playgroud)

  • @BurhanKhalid,CPython是用C语言编写的,使用像这样的itertools可以避免运行字节码.我希望它比Python循环快10-100倍 (2认同)

Thi*_*ter 5

您可以创建一个从 element 开始的迭代切片n

import itertools
def drop(it, n):
    return itertools.islice(it, n, None)
Run Code Online (Sandbox Code Playgroud)

  • 尽管很聪明,但这实际上不会删除任何内容,直到/*除非*序列被迭代。 (3认同)