如何在python中重新启动“for”循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21047108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to restart "for" loop in python ?
提问by Mero
How can I do this in python:
我怎样才能在 python 中做到这一点:
x = [1,2,3,4,5,6]
for i in x:
if i == 4:
-restart the loop from beginning-
else:
print i
So here it will print till 4 then repeat the loop
所以在这里它会打印到 4 然后重复循环
采纳答案by sphere
What about this:
那这个呢:
x = [1,2,3,4,5,6]
restart = True
while restart:
for i in x:
# add any exit condition!
# if foo == bar:
# restart = False
# break
if i == 4:
break
else:
print i
回答by Ford
Something like this perhaps? But it will loop forever...
也许是这样的?但它会永远循环......
x = [ ..... ]
restart = True
while restart:
for i in x:
if i == 4:
restart = True
break
restart = False
print i
回答by freude
I would use a recursive function for that
我会为此使用递归函数
def fun(x):
for i in x:
if i == 4:
fun(x)
else:
print i
return;
x = [1,2,3,4,5,6]
fun(x)
回答by volcano
You can't directly. Use itertools.cycle
你不能直接。使用itertools.cycle
for idx, val in enumerate(itertools.cycle(range(4))):
print v
if idx>20:
break
idxis used to break infiniteloop
idx用于打破无限循环
回答by Charles Beattie
Just wrap in a while statement.
只需包含一个 while 语句。
while True:
restart = False
for i in x:
if i == 4:
restart = True
break
else:
print i
if not restart:
break
回答by JPG
With a while loop:
使用 while 循环:
x=[1,2,3,4,5,6]
i=0
while i<len(x):
if x[i] == 4:
i=0
continue
else:
print x[i]
i+=1

