给定以下代码(不起作用):

while True:
    # Snip: print out current state
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok.lower() == "y": break 2 # This doesn't work :(
        if ok.lower() == "n": break

    # Do more processing with menus and stuff

有办法解决这个问题吗?还是我必须先检查一次,跳出输入循环,然后再检查一次,如果用户满意,再跳出外部循环?


当前回答

这不是最漂亮的方法,但在我看来,这是最好的方法。

def loop():
    while True:
    #snip: print out current state
        while True:
            ok = get_input("Is this ok? (y/n)")
            if ok == "y" or ok == "Y": return
            if ok == "n" or ok == "N": break
        #do more processing with menus and stuff

我很确定你也可以用递归解出一些东西,但我不知道这对你来说是不是一个好选择。

其他回答

解决方法有两种

举个例子:这两个矩阵相等/相同吗? 矩阵x1和矩阵x2是相同大小的,n,二维矩阵。

第一个解决方案,没有函数

same_matrices = True
inner_loop_broken_once = False
n = len(matrix1)

for i in range(n):
    for j in range(n):

        if matrix1[i][j] != matrix2[i][j]:
            same_matrices = False
            inner_loop_broken_once = True
            break

    if inner_loop_broken_once:
        break

第二个解决方案,用函数

这是我案子的最终解决方案。

def are_two_matrices_the_same (matrix1, matrix2):
    n = len(matrix1)
    for i in range(n):
        for j in range(n):
            if matrix1[i][j] != matrix2[i][j]:
                return False
    return True

将循环逻辑分解为迭代器,迭代器产生循环变量并在完成时返回——这里有一个简单的迭代器,它将图像按行/列排列,直到我们用完图像或找不到放置它们的位置:

def it(rows, cols, images):
    i = 0
    for r in xrange(rows):
        for c in xrange(cols):
            if i >= len(images):
                return
            yield r, c, images[i]
            i += 1 

for r, c, image in it(rows=4, cols=4, images=['a.jpg', 'b.jpg', 'c.jpg']):
    ... do something with r, c, image ...

这样做的优点是将复杂的循环逻辑和处理分开。

PEP 3136建议标记中断/继续。Guido拒绝了它,因为“需要这个功能的复杂代码非常罕见”。不过,PEP确实提到了一些变通方法(比如异常技术),而Guido认为在大多数情况下,使用return进行重构会更简单。

在这种情况下,正如其他人指出的那样,功能分解是可行的方法。Python 3中的代码:

def user_confirms():
    while True:
        answer = input("Is this OK? (y/n) ").strip().lower()
        if answer in "yn":
            return answer == "y"

def main():
    while True:
        # do stuff
        if user_confirms():
            break

在Python中有一个隐藏的技巧…Else结构,可以用来模拟双中断,而不需要太多的代码更改/添加。本质上,如果while条件为false,则触发else块。任何异常、continue或break都不会触发else块。有关更多信息,请参阅对“Python while语句上的Else子句”或Python while上的doc (v2.7)的回答。

while True:
    #snip: print out current state
    ok = ""
    while ok != "y" and ok != "n":
        ok = get_input("Is this ok? (y/n)")
        if ok == "n" or ok == "N":
            break    # Breaks out of inner loop, skipping else

    else:
        break        # Breaks out of outer loop

    #do more processing with menus and stuff

唯一的缺点是需要将双中断条件移到while条件中(或添加一个标志变量)。对于for循环也存在这种变化,其中else块在循环完成后被触发。