突破嵌套循环 [英] Breaking out of nested loops

查看:78
本文介绍了突破嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有比抛出异常更简单的方法来摆脱嵌套循环? (在Perl中,您可以给每个循环添加标签,至少可以继续一个外部循环.)

Is there an easier way to break out of nested loops than throwing an exception? (In Perl, you can give labels to each loop and at least continue an outer loop.)

for x in range(10):
    for y in range(10):
        print x*y
        if x*y > 50:
            "break both loops"

即,有没有比以下更好的方法了?

I.e., is there a nicer way than:

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

推荐答案

至少已提出建议,但已拒绝.我认为没有其他方法,只需重复测试或重新组织代码即可.有时有点烦人.

It has at least been suggested, but also rejected. I don't think there is another way, short of repeating the test or re-organizing the code. It is sometimes a bit annoying.

拒绝邮件中,van Rossum先生提到使用return,这真的很明智,我需要个人记住这一点. :)

In the rejection message, Mr van Rossum mentions using return, which is really sensible and something I need to remember personally. :)

这篇关于突破嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆