如何停止for循环

2024-03-28 20:32:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个代码来确定我的nxn列表中的每个元素是否相同。i、 e.[0,0],[0,0]]返回true,但[0,1],[0,0]]将返回false。我正在考虑编写一个代码,当它发现一个与第一个元素不同的元素时,它会立即停止。i、 e:

n=L[0][0]
m=len(A)
for i in range(m):
 for j in range(m):
   if
    L[i][j]==n: -continue the loop-
   else: -stop the loop-

如果L[i][j]!==n并返回false,我想停止此循环。否则返回true。我该如何实施?


Tags: the代码inloopfalsetrue元素列表
3条回答

尝试简单地使用break语句。

也可以使用以下代码作为示例:

a = [[0,1,0], [1,0,0], [1,1,1]]
b = [[0,0,0], [0,0,0], [0,0,0]]

def check_matr(matr, expVal):    
    for row in matr:
        if len(set(row)) > 1 or set(row).pop() != expVal:
            print 'Wrong'
            break# or return
        else:
            print 'ok'
    else:
        print 'empty'
check_matr(a, 0)
check_matr(b, 0)

使用breakcontinue执行此操作。在Python中,可以使用以下方法断开嵌套循环:

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

另一种方法是将所有内容包装在函数中,并使用return从循环中转义。

有几种方法可以做到这一点:

简单的方法:一个哨兵变量

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

优点:容易理解 缺点:每个循环都有附加的条件语句

老套的方法:提出一个例外

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

优点:非常简单 缺点:在语义之外使用异常

干净的方法:做一个函数

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"

优点:更干净更高效 缺点:但感觉像是C

pythonic方法:按原样使用迭代

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"

优点:仍然干净高效 缺点:你重新控制方向盘

大师之道:使用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"

优点:你会感到被黑暗力量赋予力量 缺点:会读你代码的人可能会开始讨厌你

相关问题 更多 >