简体   繁体   English

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

[英]`Itertools.cycle`: most pythonic way to take multiple steps?

I've got some list, and I'm looking to cycle through it. 我有一些清单,我正在寻找它。 The trouble is that I'm not interested in cycling through elements one at a time, but I want to cycle through by n elements at a time. 麻烦的是我对一次循环一个元素不感兴趣,但我想一次循环n元素。

For instance, if my list is l = ["a", "b", "c", "d"] , then I would want the following output: 例如,如果我的列表是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

I know that I can accomplish this with something like: 我知道我可以通过以下方式完成此任务:

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

You can use itertools.islice to advance the cycle object before calling next: 在调用next之前,您可以使用itertools.islice来推进循环对象:

from itertools import cycle, islice

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

In the documentation for itertools, there's a handy recipe for precisely this problem . 在itertools的文档中,有一个方便的方法来解决这个问题

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM