有没有办法在Python中编写无限循环?
for t in range(0,10):
if(t == 9): t= 0 # will this set t to 0 and launch infinite loop? No!
print(t)
Run Code Online (Sandbox Code Playgroud)
一般来说,有没有办法像Java中那样编写无限pythonic for循环而不使用while循环?
要一遍又一遍地迭代一个可迭代对象,您可以使用itertools.cycle:
from itertools import cycle
for t in cycle(range(0, 4)):
print(t)
Run Code Online (Sandbox Code Playgroud)
这将打印以下输出:
0
1
2
3
0
1
2
3
0
1
...
Run Code Online (Sandbox Code Playgroud)
itertools.repeat函数将无休止地返回一个对象,因此您可以遍历该对象:
import itertools
for x in itertools.repeat(1):
pass
Run Code Online (Sandbox Code Playgroud)