如何指定itertools.cycle函数的起始位置

Sie*_*ilo 4 python python-itertools python-3.x

我需要循环浏览一个列表,以便在1-4 使用之间起始位置itertools我可以在列表中循环

positions = itertools.cycle([1,2,3,4])
next(positions)
Run Code Online (Sandbox Code Playgroud)

这确实会返回下一个位置,但下次我需要从3开始怎么办?如何设置起始位置?

我需要经常更改起始位置,我不能将列表更改为从3开始.

Mar*_*ers 7

你不能设置一个起始位置; 它总是从给定序列开始的地方开始.

您可以将循环移动几步,然后再根据需要使用它.使用itertools.islice()跳过一些项目:

from itertools import islice

starting_at_three = islice(positions, 2, None)
Run Code Online (Sandbox Code Playgroud)

你传入iterable,然后是一个开始和结束值; None这意味着islice()迭代器将永远持续或直到底层positions迭代器耗尽.

演示:

>>> from itertools import islice, cycle
>>> positions = cycle([1, 2, 3, 4])
>>> starting_at_three = islice(positions, 2, None)
>>> next(starting_at_three)
3
>>> next(starting_at_three)
4
>>> next(starting_at_three)
1
Run Code Online (Sandbox Code Playgroud)

另一种选择是传递不同的顺序; 你可以传递一下[3, 4, 1, 2].