如何停止for循环

新手上路,请多包涵

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

 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。否则返回真。我将如何着手实施这个?

原文由 LostLin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 299
2 个回答

使用 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 从循环中退出。

原文由 Alexander Gessler 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

简单方法:哨兵变量

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

优点:易于理解缺点:每个循环都有额外的条件语句

hacky 方式:抛出异常

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

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

干净的方式:创建一个函数

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(cell != first for col in iterable for cell in col)

if is_different_value(L):
  print "Doh"

优点:你会感受到黑暗力量的力量 缺点:阅读你代码的人可能会开始不喜欢你

原文由 e-satis 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题