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

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

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


当前回答

使用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倍。

其他回答

keeplooping = True
while keeplooping:
    # Do stuff
    while keeplooping:
          # Do some other stuff
          if finisheddoingstuff():
              keeplooping = False

或者类似的东西。

您可以在内部循环中设置一个变量,并在内部循环退出后立即在外部循环中检查它,如果合适的话可以中断。我有点喜欢GOTO方法,前提是你不介意使用愚人节的笑话模块——它不是python的,但它确实有意义。

我来这里的原因是我有一个外循环和一个内循环,像这样:

for x in array:
  for y in dont_use_these_values:
    if x.value==y:
      array.remove(x)  # fixed, was array.pop(x) in my original answer
      continue

  do some other stuff with x

正如你所看到的,它不会去下一个x,而是去下一个y。

我发现解决这个问题的简单方法是遍历数组两次:

for x in array:
  for y in dont_use_these_values:
    if x.value==y:
      array.remove(x)  # fixed, was array.pop(x) in my original answer
      continue

for x in array:
  do some other stuff with x

我知道这是OP问题的一个具体案例,但我发布它是希望它能帮助人们以不同的方式思考他们的问题,同时保持事情简单。

你可以使用一个标志来打破循环:

if found:
  break

这里,'found'是标志,你最初将它设置为False,然后在循环中使用这段代码。

found = False
for table_height in range(500):
  if found:
    break

下面是三个for循环的完整代码:

found = False
for table_height in range(500):
  if found:
    break
  for cat_height in range(500):
    if found:
      break

    for tort_height in range(500):
      equation1 = table_height + cat_height == tort_height + 170
      equation2 = table_height + tort_height == cat_height + 130
      if equation1 and equation2:
        print('table', table_height, '  cat', cat_height, '  tortoise', tort_height)
        found = True
        break

在这段代码中,如果等式1和等式2为True,它将设置'found'标志为True,并跳出最里面的for循环,它也将跳出其他两个for循环,因为'found'为True。

我想提醒你,Python中的函数可以在代码中间创建,并且可以透明地访问周围的变量以进行读取,也可以通过非局部或全局声明进行写入。

所以你可以使用一个函数作为“易碎的控制结构”,定义一个你想要返回的地方:

def is_prime(number):

    foo = bar = number

    def return_here():
        nonlocal foo, bar
        init_bar = bar
        while foo > 0:
            bar = init_bar
            while bar >= foo:
                if foo*bar == number:
                    return
                bar -= 1
            foo -= 1

    return_here()

    if foo == 1:
        print(number, 'is prime')
    else:
        print(number, '=', bar, '*', foo)

>>> is_prime(67)
67 is prime
>>> is_prime(117)
117 = 13 * 9
>>> is_prime(16)
16 = 4 * 4

我的第一反应是将嵌套循环重构为一个函数,并使用return来跳出。