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

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

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


当前回答

while True:
    # Snip: print out current state
    while True:
        ok = get_input("Is this ok? (y/n)")
        if ok.lower() == "y": 
            break_2 = True
        if ok.lower() == "n": 
            break
    if break_2:
        break

其他回答

这是另一种简短的方法。缺点是你只能打破外部循环,但有时这正是你想要的。

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

这使用了for / else结构:为什么python在for和while循环之后使用'else' ?

关键洞见:似乎只有外部循环总是会破裂。但如果内环不破裂,外环也不会破裂。

这里的continue语句很神奇。它在for-else从句中。根据定义,如果没有内部断裂,就会发生这种情况。在这种情况下,继续巧妙地绕过外部中断。

尝试使用无限发电机。

from itertools import repeat
inputs = (get_input("Is this ok? (y/n)") for _ in repeat(None))
response = (i.lower()=="y" for i in inputs if i.lower() in ("y", "n"))

while True:
    #snip: print out current state
    if next(response):
        break
    #do more processing with menus and stuff

使用numpy.ndindex可以简单地将多个循环转换为单个、可破坏的循环

for i in range(n):
  for j in range(n):
    val = x[i, j]
    break # still inside the outer loop!

for i, j in np.ndindex(n, n):
  val = x[i, j]
  break # you left the only loop there was!

您确实需要索引到对象中,而不是显式地遍历值,但至少在简单的情况下,它似乎比大多数答案所建议的要简单大约2-20倍。

Break for外层和内部while循环:

while True:
    while True:
        print('Breaks inner "while" loop')
        break # Here
    print('Breaks outer "while" loop')
    break # Here

或者,用if语句中断外部和内部while循环:

while True:
    while True:
        if True:
            print('Breaks inner "while" loop')
            break # Here
    print('Breaks outer "while" loop')
    break # Here

输出:

Breaks inner "while" loop
Breaks outer "while" loop

Break for outer和inner for循环:

for _ in iter(int, 1):
    for _ in iter(int, 1):
        print('Breaks inner "for" loop')
        break # Here
    print('Breaks outer "for" loop')
    break # Here

或者,用if语句打破外部和内部for循环:

for _ in iter(int, 1):
    for _ in iter(int, 1):
        if True:
            print('Breaks inner "for" loop')
            break # Here
    print('Breaks outer "for" loop')
    break # Here

输出:

Breaks inner "for" loop
Breaks outer "for" loop

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

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 ...

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