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

问题描述

基本上,我需要一种方法来将控制权返回到 for 循环的开头并在满足特定条件时采取行动后实际重新启动整个迭代过程.

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.

我想要做的是:

    for index, item in enumerate(list2):
    if item == '||' and list2[index-1] == '||':
        del list2[index]
        *<some action that resarts the whole process>*

那样,如果 ['berry','||','||','||','pancake] 在列表中,我会得到:

That way, if ['berry','||','||','||','pancake] is inside the list, I'll wind up with:

['berry','||','pancake'] 代替.

['berry','||','pancake'] instead.

谢谢!

推荐答案

我不确定您所说的重新启动"是什么意思.你是想从头开始迭代,还是直接跳过当前的迭代?

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?

如果是后者,那么 for 循环支持 continue 就像 while 循环一样:

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

上面将打印从 0 到 9 的数字,除了 5.

The above will print the numbers from 0 to 9, except for 5.

如果您说的是从 for 循环的开头重新开始,那么除了手动"之外别无他法,例如将其包装在 while 中代码>循环:

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

上面将打印从 0 到 5 的数字,然后再次从 0 开始,以此类推(我知道这不是一个很好的例子).

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 循环的方法,类似于“继续";for while 循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:52