`Itertools.cycle`:大多数pythonic方式采取多个步骤?

时间:2017-01-31 23:39:49

标签: python python-3.x generator itertools

我有一些清单,我正在寻找它。麻烦的是我对一次循环一个元素不感兴趣,但我希望一次循环n个元素。

例如,如果我的列表是l = ["a", "b", "c", "d"],那么我想要以下输出:

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

我知道我可以通过以下方式实现这一目标:

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

2 个答案:

答案 0 :(得分:2)

您可以使用itertools.islice推进循环对象,然后再调用下一个:

from itertools import cycle, islice

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

答案 1 :(得分: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)