how to stop a for loop

前端 未结 8 1952
长情又很酷
长情又很酷 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:25

    In order to jump out of a loop, you need to use the break statement.

    n=L[0][0]
    m=len(A)
    for i in range(m):
     for j in range(m):
       if L[i][j]!=n:
           break;
    

    Here you have the official Python manual with the explanation about break and continue, and other flow control statements:

    http://docs.python.org/tutorial/controlflow.html

    EDITED: As a commenter pointed out, this does only end the inner loop. If you need to terminate both loops, there is no "easy" way (others have given you a few solutions). One possiblity would be to raise an exception:

    def f(L, A):
        try:
            n=L[0][0]
            m=len(A)
            for i in range(m):
                 for j in range(m):
                     if L[i][j]!=n:
                         raise RuntimeError( "Not equal" )
            return True
        except:
            return False
    

提交回复
热议问题