Python - 从所有循环中`break`
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21293336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - `break` out of all loops
提问by Vader
I am using multiple nested forloops. In the last loop there is an ifstatement. When evaluated to Trueall the forloops should stop, but that does not happen. It only breaks out of the innermost forloop, and than it keeps on going. I need all loops to come to a stop if the breakstatement is encountered.
我正在使用多个嵌套for循环。在最后一个循环中有一个if语句。当对True所有for循环进行评估时应该停止,但这不会发生。它只是break在最内层的for循环之外,然后继续前进。如果break遇到该语句,我需要所有循环停止。
My code:
我的代码:
for i in range(1, 1001):
for i2 in range(i, 1001):
for i3 in range(i2, 1001):
if i*i + i2*i2 == i3*i3 and i + i2 + i3 == 1000:
print i*i2*i3
break
采纳答案by Vader
You should put your loops inside a function and then return:
你应该把你的循环放在一个函数中,然后返回:
def myfunc():
for i in range(1, 1001):
for i2 in range(i, 1001):
for i3 in range(i2, 1001):
if i*i + i2*i2 == i3*i3 and i + i2 + i3 == 1000:
print i*i2*i3
return # Exit the function (and stop all of the loops)
myfunc() # Call the function
Using returnimmediately exits the enclosing function. In the process, all of the loops will be stopped.
使用return立即退出封闭函数。在此过程中,所有循环都将停止。
回答by dugres
You can raise an exception
您可以引发异常
try:
for a in range(5):
for b in range(5):
if a==b==3:
raise StopIteration
print b
except StopIteration: pass
回答by andrewgrz
Not sure if this the cleanest way possible to do it but you could do a bool check at the top of every loop.
不确定这是否是最干净的方法,但您可以在每个循环的顶部进行 bool 检查。
do_loop = True
for i in range(1, 1001):
if not do_loop:
break
for i2 in range(i, 1001):
# [Loop code here]
# set do_loop to False to break parent loops
回答by greole
why not use a generator expression:
为什么不使用生成器表达式:
def my_iterator()
for i in range(1, 1001):
for i2 in range(i, 1001):
for i3 in range(i2, 1001):
yield i,i2,i3
for i,i2,i3 in my_iterator():
if i*i + i2*i2 == i3*i3 and i + i2 + i3 == 1000:
print i*i2*i3
break

