How to break out of multiple loops?

后端 未结 30 3262
情书的邮戳
情书的邮戳 2020-11-21 05:48

Given the following code (that doesn\'t work):

while True:
    #snip: print out current state
    while True:
        ok = get_input(\"Is this ok? (y/n)\")
          


        
30条回答
  •  不知归路
    2020-11-21 06:20

    An easy way to turn multiple loops into a single, breakable loop is to use 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!
    

    You do have to index into your objects, as opposed to being able to iterate through the values explicitly, but at least in simple cases it seems to be approximately 2-20 times simpler than most of the answers suggested.

提交回复
热议问题