Pythonic solution to drop N values from an iterator

匆匆过客 提交于 2020-07-18 10:41:10

问题


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()

But this is IMO not as elegant as Python code should be. Is there a better approach I am missing here?


回答1:


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)

If you don't need the special behaviour when n is None, you can just use

next(islice(iterator, n, n), None)



回答2:


You can create an iterative slice that starts at element n:

import itertools
def drop(it, n):
    return itertools.islice(it, n, None)



回答3:


You could do this with fancy use of itertools.dropwhile, but I would hesitate to call it in any way elegant:

def makepred(n):
   def pred(x):
      pred.count += 1
      return pred.count < n
   pred.count = 0
   return pred

itertools.dropwhile(it, makepred(5))

I really don't recommend this, though - relying on the side effects of a predicate function is very much on the odd side.



来源:https://stackoverflow.com/questions/11113803/pythonic-solution-to-drop-n-values-from-an-iterator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!