2017-01-31 4 views
0

私はいくつかのリストを持っており、私はそれを巡って探しています。問題は、一度に1つずつ要素を循環させることに興味がないことですが、私は一度にn要素を循環させたいと思います。`Itertools.cycle`:複数のステップを踏む最もpythonicな方法?

>>> from itertools import cycle 
>>> gen = cycle(l) 
>>> next(gen, 4) # I know this doesn't work -- take as pseudocode 
d 
>>> next(gen, 3) 
c 

私は私のようなもので、これを達成することができます知っている:あなたはitertools.isliceを使用することができます

def generator_step(g, n): 
    for item in range(n): 
     next(g) 
    return item 
+0

は、4つのステップになるはずということですか? 2回目の呼び出しでは4ステップではありません。 – user2357112

+0

@ user2357112 fixed、申し訳ありません – Newb

+1

一定時間のジャンプについては、リストとインデックスを維持するだけです。 'itertools.cycle'イテレータでそれを得ることはできません。 ( 'collections.deque'とその' rotate'メソッドも考慮する価値がありますが、それは一定時間ではありません) – user2357112

答えて

1

私のリストがl = ["a", "b", "c", "d"]ある場合

は例えば、私は次の出力を望みます次の呼び出しの前にサイクルオブジェクトを進める:

from itertools import cycle, islice 

c = cycle(l) 
n = 4 
print(next(islice(c, n-1, n))) 
# d 
+0

'islice'関数は3つの引数を取るのはなぜですか?私は 'islice(c、n)'を使って満足できる出力を得ています。 – Newb

+0

これは、あなたが望むものではない 'next'を呼び出すときにのみスライスの最初の項目を与えます –

1

itertoolsのドキュメントには、handy recipe for precisely this problemがあります。

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) 
関連する問題