Python:继续外循环中的下一个迭代 [英] Python: Continuing to next iteration in outer loop
问题描述
我想知道是否有任何内置方法可以继续进行python外循环中的下一次迭代.例如,考虑以下代码:
I wanted to know if there are any built-in ways to continue to next iteration in outer loop in python. For example, consider the code:
for ii in range(200):
for jj in range(200, 400):
...block0...
if something:
continue
...block1...
我希望此continue语句退出jj循环并转到ii循环中的下一项.我可以通过其他方式(通过设置标志变量)来实现此逻辑,但是有没有简单的方法可以做到这一点,或者就像要求太多?
I want this continue statement to exit the jj loop and goto next item in the ii loop. I can implement this logic in some other way (by setting a flag variable), but is there an easy way to do this, or is this like asking for too much?
推荐答案
for i in ...:
for j in ...:
for k in ...:
if something:
# continue loop i
在一般情况下,当您有多个循环级别并且break
对您不起作用(因为您要继续上一个循环,而不是当前循环的右上一个)时,可以执行一个以下
In a general case, when you have multiple levels of looping and break
does not work for you (because you want to continue one of the upper loops, not the one right above the current one), you can do one of the following
def inner():
for j in ...:
for k in ...:
if something:
return
for i in ...:
inner()
缺点是您可能需要将以前在范围内的一些变量传递给该新函数.您既可以将它们作为参数传递,也可以在对象上使它们成为实例变量(如果有意义,仅为此函数创建一个新对象),也可以将全局变量,单例(无论是什么)(ehm,ehm).
The disadvantage is that you may need to pass to that new function some variables, which were previously in scope. You can either just pass them as parameters, make them instance variables on an object (create a new object just for this function, if it makes sense), or global variables, singletons, whatever (ehm, ehm).
或者您可以将inner
定义为嵌套函数,并使其仅捕获所需的内容(可能会更慢?)
Or you can define inner
as a nested function and let it just capture what it needs (may be slower?)
for i in ...:
def inner():
for j in ...:
for k in ...:
if something:
return
inner()
使用例外
从哲学上讲,这是例外,需要时,通过结构化的编程构建块(如果有,为时,为时)中断程序流.
Use exceptions
Philosophically, this is what exceptions are for, breaking the program flow through the structured programming building blocks (if, for, while) when necessary.
优点是您不必将单个代码分成多个部分.如果这是您在用Python编写代码时正在设计的某种计算,那么这很好.在早期引入抽象可能会减慢您的速度.
The advantage is that you don't have to break the single piece of code into multiple parts. This is good if it is some kind of computation that you are designing while writing it in Python. Introducing abstractions at this early point may slow you down.
这种方法的坏处在于,解释器/编译器作者通常会认为例外是例外情况,因此会相应地对其进行优化.
Bad thing with this approach is that interpreter/compiler authors usually assume that exceptions are exceptional and optimize for them accordingly.
class ContinueI(Exception):
pass
continue_i = ContinueI()
for i in ...:
try:
for j in ...:
for k in ...:
if something:
raise continue_i
except ContinueI:
continue
为此创建一个特殊的异常类,这样就不会冒意外使某些其他异常静默的风险.
Create a special exception class for this, so that you don't risk accidentally silencing some other exception.
我确定还有其他解决方案.
I am sure there are still other solutions.
这篇关于Python:继续外循环中的下一个迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!