n
イテレータから値を削除するPythonicソリューションはありますか? n
次のように値を破棄するだけでこれを行うことができます。
def _drop(it, n):
for _ in xrange(n):
it.next()
しかし、これは IMO であり、Python コードがあるべきほどエレガントではありません。ここで見逃しているより良いアプローチはありますか?
「消費」レシピを探していると思います
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)
is のときの特別な動作が必要ない場合n
はNone
、そのまま使用できます
next(islice(iterator, n, n), None)
element から始まる反復スライスを作成できますn
。
import itertools
def drop(it, n):
return itertools.islice(it, n, None)
を巧妙に使用してこれを行うこともできitertools.dropwhile
ますが、それをエレガントと呼ぶのはためらっています。
def makepred(n):
def pred(x):
pred.count += 1
return pred.count < n
pred.count = 0
return pred
itertools.dropwhile(it, makepred(5))
ただし、これはお勧めしません。述語関数の副作用に依存することは、非常に奇妙です。