Pythonic solution to remove N values ​​from an iterator

Is there a python solution to remove n values ​​from an iterator? You can do this by simply dropping the n values ​​as follows:

 def _drop(it, n): for _ in xrange(n): it.next() 

But this IMO is not as elegant as Python code. Is there a better approach that I'm missing here?

+6
source share
3 answers

I believe you are looking for a 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) 

Unless you require special behavior, if n is None , you can simply use

 next(islice(iterator, n, n), None) 
+8
source

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

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

You can do this with the fantastic use of itertools.dropwhile , but I would be embarrassed to call it somehow 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 do not recommend this, though - relying on the side effects of the predicate function is very strong on the odd side.

0
source

Source: https://habr.com/ru/post/918534/


All Articles