Stu*_*Gla 15
这是使用上下文管理器打破多个嵌套块的方法:
import contextlib
@contextlib.contextmanager
def escapable():
class Escape(RuntimeError): pass
class Unblock(object):
def escape(self):
raise Escape()
try:
yield Unblock()
except Escape:
pass
Run Code Online (Sandbox Code Playgroud)
您可以使用它来打破多个循环:
with escapable() as a:
for i in xrange(30):
for j in xrange(30):
if i * j > 6:
a.escape()
Run Code Online (Sandbox Code Playgroud)
你甚至可以嵌套它们:
with escapable() as a:
for i in xrange(30):
with escapable() as b:
for j in xrange(30):
if i * j == 12:
b.escape() # Break partway out
if i * j == 40:
a.escape() # Break all the way out
Run Code Online (Sandbox Code Playgroud)
虽然有理由在语言构造中包含命名循环,但您可以轻松地在python中避免它而不会丢失可读性.python中引用示例的实现
>>> try:
for i in xrange(0,5):
for j in xrange(0,6):
if i*j > 6:
print "Breaking"
raise StopIteration
print i," ",j
except StopIteration:
print "Done"
0 0
0 1
0 2
0 3
0 4
0 5
1 0
1 1
1 2
1 3
1 4
1 5
2 0
2 1
2 2
2 3
Breaking
Done
>>>
Run Code Online (Sandbox Code Playgroud)
我通过将内部循环放在一个返回(以及其他)布尔值的函数中来解决这个问题,该布尔值用作断开条件.
我想你应该试试这个.这是非常pythonic,简单和可读.