[英]`Itertools.cycle`: most pythonic way to take multiple steps?
我有一些清單,我正在尋找它。 麻煩的是我對一次循環一個元素不感興趣,但我想一次循環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
在調用next之前,您可以使用itertools.islice
來推進循環對象:
from itertools import cycle, islice
c = cycle(l)
n = 4
print(next(islice(c, n-1, n)))
# d
在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.