how to stop a for loop

前端 未结 8 1949
长情又很酷
长情又很酷 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条回答
  •  猫巷女王i
    2020-11-27 03:26

    There are several ways to do it:

    The simple Way: a sentinel variable

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

    Pros: easy to understand Cons: additional conditional statement for every loop

    The hacky Way: raising an exception

    n = L[0][0]
    m = len(A)
    
    try:
      for x in range(3):
        for z in range(3):
         if L[i][j] != n: 
           raise StopIteration
    except StopIteration:
       pass
    

    Pros: very straightforward Cons: you use Exception outside of their semantic

    The clean Way: make a function

    def is_different_value(l, elem, size):
      for x in range(size):
        for z in range(size):
         if l[i][j] != elem: 
           return True
      return False
    
    if is_different_value(L, L[0][0], len(A)):
      print "Doh"
    

    pros: much cleaner and still efficient cons: yet feels like C

    The pythonic way: use iteration as it should be

    def is_different_value(iterable):
      first = iterable[0][0]
      for l in iterable:
        for elem in l:
           if elem != first: 
              return True
      return False
    
    if is_different_value(L):
      print "Doh"
    

    pros: still clean and efficient cons: you reinvdent the wheel

    The guru way: use any():

    def is_different_value(iterable):
      first = iterable[0][0]
      return  any(any((cell != first for cell in col)) for elem in iterable)):
    
    if is_different_value(L):
      print "Doh"
    

    pros: you'll feel empowered with dark powers cons: people that will read you code may start to dislike you

提交回复
热议问题