【发布时间】:2011-10-18 17:04:18
【问题描述】:
有几种方法可以打破几个嵌套循环
他们是:
1) 使用中断继续
for x in xrange(10):
for y in xrange(10):
print x*y
if x*y > 50:
break
else:
continue # only executed if break was not used
break
2) 使用返回
def foo():
for x in range(10):
for y in range(10):
print x*y
if x*y > 50:
return
foo()
3) 使用特殊异常
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
我曾想过可能有其他方法可以做到这一点。 它是通过使用 StopIteration 将异常直接发送到外循环。 我写了这段代码
it = iter(range(10))
for i in it:
for j in range(10):
if i*j == 20:
raise StopIteration
不幸的是,StopIteration 没有被任何 for 循环捕获,并且该代码产生了丑陋的 Traceback。 我认为这是因为 StopIteration 不是从迭代器 it 内部发送的。 (这是我的猜测,我不确定)。
有什么方法可以将 StopIteration 发送到外循环?
谢谢!
【问题讨论】:
标签: python loops for-loop iterator stopiteration