我如何在python中执行此操作:
x = [1,2,3,4,5,6]
for i in x:
if i == 4:
-restart the loop from beginning-
else:
print i
所以这里它将打印到4然后重复循环
答案 0 :(得分:7)
这个怎么样:
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
答案 1 :(得分:2)
你不能直接。使用 itertools.cycle
for idx, val in enumerate(itertools.cycle(range(4))):
print v
if idx>20:
break
idx 用于打破infiniteloop
答案 2 :(得分:1)
也许这样的事情?但它会永远循环......
x = [ ..... ]
restart = True
while restart:
for i in x:
if i == 4:
restart = True
break
restart = False
print i
答案 3 :(得分:0)
只需用while语句换行。
while True:
restart = False
for i in x:
if i == 4:
restart = True
break
else:
print i
if not restart:
break
答案 4 :(得分:0)
使用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
答案 5 :(得分:-4)
我会为那个
使用递归函数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)