从迭代器外部向循环发送StopIteration

ovg*_*vin 7 python iterator loops for-loop stopiteration

有几种方法可以打破几个嵌套循环

他们是:

1)使用break-continue

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
Run Code Online (Sandbox Code Playgroud)

2)使用退货

def foo():
    for x in range(10):
        for y in range(10):
            print x*y
            if x*y > 50:
                return
foo()
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我有一些想法,可能还有其他方法可以做到这一点.它是通过使用StopIteration异常直接发送到外部循环的.我写了这段代码

it = iter(range(10))
for i in it:
    for j in range(10):
        if i*j == 20:
            raise StopIteration
Run Code Online (Sandbox Code Playgroud)

不幸的是,StopIteration还没有被任何for循环捕获,并且该代码产生了一个丑陋的Traceback.我想这是因为StopIteration异常是无法从iterator内发送它.(这是我的猜测,我不确定).

有什么办法可以将StopIteration发送到外循环吗?

谢谢!

And*_*ark 4

您可以使用协程执行以下操作:

def stoppable_iter(iterable):
    it = iter(iterable)
    for v in it:
        x = yield v
        if x:
            yield
            return
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它:

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
Run Code Online (Sandbox Code Playgroud)

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

>>> 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
Run Code Online (Sandbox Code Playgroud)