Breaking out of nested loops
Possible Duplicate:
How to break out of multiple loops in Python?
Is there an easier way to break out of nested loops than throwing an exception? (In Perl, you can give labels to each loop and at least continue an outer loop.)
for x in range(10):
for y in range(10):
print x*y
if x*y > 50:
"break both loops"
Ie, is there a nicer way than:
class BreakIt(Exception): pass
try:
for x in range(10):
for y in range(10):
print x*y
if x*y > 50:
raise BreakIt
except BreakIt:
pass
It has at least been suggested, but also rejected. I don't think there is another way, short of repeating the test or re-organizing the code. It is sometimes a bit annoying.
In the rejection message, Mr van Rossum mentions using return
, which is really sensible and something I need to remember personally. :)
for x in xrange(10):
for y in xrange(10):
print x*y
if x*y > 50:
break
else:
continue # only executed if the inner loop did NOT break
break # only executed if the inner loop DID break
对于更深层次的循环也是一样:
for x in xrange(10):
for y in xrange(10):
for z in xrange(10):
print x,y,z
if x*y*z == 30:
break
else:
continue
break
else:
continue
break
If you're able to extract the loop code into a function, a return
statement can be used to exit the outermost loop at any time.
def foo():
for x in range(10):
for y in range(10):
print x*y
if x*y > 50:
return
foo()
If it's hard to extract that function you could use an inner function, as @bjd2385 suggests, eg
def your_outer_func():
...
def inner_func():
for x in range(10):
for y in range(10):
print x*y
if x*y > 50:
return
inner_func()
...
链接地址: http://www.djcxy.com/p/6184.html
上一篇: 局部变量的内存是否可以在其范围之外访问?
下一篇: 打破嵌套循环