问题
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