8

nイテレータから値を削除するPythonicソリューションはありますか? n次のように値を破棄するだけでこれを行うことができます。

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

しかし、これは IMO であり、Python コードがあるべきほどエレガントではありません。ここで見逃しているより良いアプローチはありますか?

4

3 に答える 3

10

「消費」レシピを探していると思います

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 のときの特別な動作が必要ない場合nNone、そのまま使用できます

next(islice(iterator, n, n), None)
于 2012-06-20T06:20:40.397 に答える
4

element から始まる反復スライスを作成できますn

import itertools
def drop(it, n):
    return itertools.islice(it, n, None)
于 2012-06-20T06:20:48.030 に答える
0

を巧妙に使用してこれを行うこともでき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))

ただし、これはお勧めしません。述語関数の副作用に依存することは、非常に奇妙です。

于 2012-06-20T06:25:08.740 に答える