Python - 重启for循环的方式,类似于“continue”为while循环? [英] Python - Way to restart a for loop, similar to "continue" for while loops?

查看:170
本文介绍了Python - 重启for循环的方式,类似于“continue”为while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我需要一种方法来将控制返回到for循环的开始,并在采取行动后实际重新开始整个迭代过程如果满足某些条件。



我试图做的是:

  for index,item in enumerate list2):
if item =='||'and list2 [index-1] =='||':
del list2 [index]
*<整个过程> *

如果['berry','||','|| '','||','pancake]在列表中,我将结束:
$ b <'berry','||','pancake' ]

谢谢!

解决方案

我不确定你的意思是重新启动。如果是后者,那么代表 $ c $>循环支持继续就像 while 循环:

 我在xrange(10)中:
if i == 5:
continue
print i


如果你正在谈论从开始为循环开始,除了手动之外没有办法做到这一点,例如把它包装在一个<$ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆