相关疑难解决方法(0)

从迭代器外部向循环发送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: …
Run Code Online (Sandbox Code Playgroud)

python iterator loops for-loop stopiteration

7
推荐指数
1
解决办法
3069
查看次数

标签 统计

for-loop ×1

iterator ×1

loops ×1

python ×1

stopiteration ×1