gpt4 book ai didi

python - 从迭代器外部将 StopIteration 发送到 for 循环

转载 作者:太空狗 更新时间:2023-10-29 21:35:28 25 4
gpt4 key购买 nike

有几种方法可以跳出几个嵌套循环

它们是:

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 发送到外循环?

谢谢!

最佳答案

你可以用协程做这样的事情:

def stoppable_iter(iterable):
it = iter(iterable)
for v in it:
x = yield v
if x:
yield
return

然后像这样使用它:

it = stoppable_iter(range(10))
for i in it:
for j in range(10):
print i, j
if i*j == 20:
it.send(StopIteration) # or any value that evaluates as True
break

以及它如何工作的一个简短示例:

>>> t = stoppable_iter(range(10))
>>> t.next()
0
>>> t.next()
1
>>> t.send(StopIteration)
>>> t.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration

关于python - 从迭代器外部将 StopIteration 发送到 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6920206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com