【问题标题】:How to break from inner loop to the beginning of the outer loop如何从内循环中断到外循环的开头
【发布时间】:2017-10-23 11:13:32
【问题描述】:

从内部循环中断的最佳方法是什么,以便我到达外部循环的开头

while condition:
    while second_condition:
        if some_condition_here:
            get_to_the_beginning_of_first_loop

现在我得到了类似的东西

while condition:
    while second_condition:
        if condition1:
            break
    if condition1:
        continue

【问题讨论】:

    标签: python


    【解决方案1】:

    Python 可以为while 循环选择else: 子句。如果您调用break,则会调用它,因此它们是等价的:

    while condition:
        while second_condition:
            if condition1:
                break
        if condition1:
            continue
        do_something_if_no_break()
    

    和:

    while condition:
        while second_condition:
            if condition1:
                break
        else:
            do_something_if_no_break()
    

    【讨论】:

    • 哇。那是我第一次听说这个。
    • @KaushikNP 更正常的用法是for x in mylist: if x==5: break else: print("No five found!")
    • 不错。很好的例子。
    • condition1 使用在第二个块内定义的一些变量在这种情况下该怎么办。?
    • @Poojan 如果您在我的回答中使用else 技巧,那么您只需要在第二个块中使用condition1,所以我看不到问题。
    【解决方案2】:

    只是在@ArthurTacca 的答案的基础上,您使用Python 的else 运算符来创建一个优雅的、任意深度的中断功能:

    # Copied from ArthurTacca
    while condition:
        while second_condition:
            if condition1:
                break
        else:
            do_something_if_no_break()
            # Minor addition
            continue  # This avoids the break below
        break  # Fires if the inner loop hit a "break"
    

    请注意,这种 else:continue/break 模式可以重复到任意深度,也适用于 for 循环。

    【讨论】:

      猜你喜欢
      • 2016-12-31
      • 2013-06-07
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      相关资源
      最近更新 更多