how to stop a for loop

前端 未结 8 1866
长情又很酷
长情又很酷 2020-11-27 03:00

I\'m writing a code to determine if every element in my nxn list is the same. i.e. [[0,0],[0,0]] returns true but [[0,1],[0,0]] will return false.

相关标签:
8条回答
  • 2020-11-27 03:38

    Use the break statement: http://docs.python.org/reference/simple_stmts.html#break

    0 讨论(0)
  • 2020-11-27 03:39

    Use break and continue to do this. Breaking nested loops can be done in Python using the following:

    for a in range(...):
       for b in range(..):
          if some condition:
             # break the inner loop
             break
       else:
          # will be called if the previous loop did not end with a `break` 
          continue
       # but here we end up right after breaking the inner loop, so we can
       # simply break the outer loop as well
       break
    

    Another way is to wrap everything in a function and use return to escape from the loop.

    0 讨论(0)
提交回复
热议问题