Python - 重启for循环的方式,类似于“continue”为while循环? [英] Python - Way to restart a for loop, similar to "continue" for while loops?
问题描述
我试图做的是:
for index,item in enumerate list2):
if item =='||'and list2 [index-1] =='||':
del list2 [index]
*<整个过程> *
如果['berry','||','|| '','||','pancake]在列表中,我将结束:
$ b <'berry','||','pancake' ]
谢谢!
我不确定你的意思是重新启动。如果是后者,那么代表$ c> $ c $>循环支持
继续
就像 while
循环:
我在xrange(10)中:
if i == 5:
continue
print i
$ c $上面将打印从0到9的数字,除了5以外。
如果你正在谈论从开始为
循环开始,除了手动之外没有办法做到这一点,例如把它包装在一个<$ c
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $''$'$' b should_restart = False
for xrange(10):
print i
if i == 5:
should_restart = True
break
code $
$ b $ p
$ b
上面会打印0到5的数字,然后从0开始重复,等等(不是真的一个很好的例子,我知道)。
Basically, I need a way to return control to the beginning of a for loop and actually restart the entire iteration process after taking an action if a certain condition is met.
What I'm trying to do is this:
for index, item in enumerate(list2):
if item == '||' and list2[index-1] == '||':
del list2[index]
*<some action that resarts the whole process>*
That way, if ['berry','||','||','||','pancake] is inside the list, I'll wind up with:
['berry','||','pancake'] instead.
Thanks!
解决方案 I'm not sure what you mean by "restarting". Do you want to start iterating over from the beginning, or simply skip the current iteration?
If it's the latter, then for
loops support continue
just like while
loops do:
for i in xrange(10):
if i == 5:
continue
print i
The above will print the numbers from 0 to 9, except for 5.
If you're talking about starting over from the beginning of the for
loop, there's no way to do that except "manually", for example by wrapping it in a while
loop:
should_restart = True
while should_restart:
should_restart = False
for i in xrange(10):
print i
if i == 5:
should_restart = True
break
The above will print the numbers from 0 to 5, then start over from 0 again, and so on indefinitely (not really a great example, I know).
这篇关于Python - 重启for循环的方式,类似于“continue”为while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!