跳回python迭代器

Tom*_*sky 0 python for-loop python-3.x

做这样的C代码最有效的方法是什么

for(int i = 0; i < 10; i++) {
    printf("%d\n", i);
    if(i == 5)
        i = 1;
}
Run Code Online (Sandbox Code Playgroud)

在python中,输出就是

0
1
2
3
4
5
1
2
3
4
5
1
Run Code Online (Sandbox Code Playgroud)

我知道有下一个()的范围

iterator = iter(range(0, 10))
for i in iterator:
    next(iterator)
    print(i)
Run Code Online (Sandbox Code Playgroud)

所以这段代码会打印每一个数字,但我不知道如何跳回for循环.

Ste*_*uch 7

你可以永远循环使用itertools.cycle(),你可以itertools.chain()用来附加起始条件,如:

import itertools as it
for i in it.chain((0,), it.cycle(range(1, 6))):
    print(i)
Run Code Online (Sandbox Code Playgroud)

结果:

0
1
2
3
4
5
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)