跳出两层循环

python没有提供goto类似的语法特性,平常跳出两层循环一般是把两层循环包装在一个函数里,用return得方式直接返回,或者设置一个flag,今天在st ackoverflow上看到一个实现方式,感觉挺好得,地址: http://stackoverflow.com/questions/189645/how- to-break-out-of-multiple-loops-in-python

for a in xrange(10):
    for b in xrange(20):
        if something(a, b):
            # Break the inner loop...
            break
    else:
        # Continue if the inner loop wasn't broken.
        continue
    # Inner loop was broken, break the outer.
    break

发表评论

电子邮件地址不会被公开。 必填项已用*标注

This blog is kept spam free by WP-SpamFree.