如何停止for循环

Los*_*Lin 42 python

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

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-
Run Code Online (Sandbox Code Playgroud)

如果L[i][j]!==n 返回false,我想停止这个循环.否则返回true.我将如何实现这一目标?

Ale*_*ler 74

使用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
Run Code Online (Sandbox Code Playgroud)

另一种方法是将所有内容包装在函数中并用于return从循环中逃脱.

  • 哇,希望C#有'for ... else`构造! (3认同)
  • 哦,我希望C++,Java,...同样:.-) (2认同)
  • 创意答案+1,但这真的值得吗?你可以简单地 make if found:break 。更短,更容易阅读。 (2认同)

e-s*_*tis 49

有几种方法可以做到:

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

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
Run Code Online (Sandbox Code Playgroud)

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

hacky Way:提出异常

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
Run Code Online (Sandbox Code Playgroud)

优点:非常简单缺点:你在语义之外使用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"
Run Code Online (Sandbox Code Playgroud)

专业人士:更清洁,更有效的缺点:但感觉就像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"
Run Code Online (Sandbox Code Playgroud)

专业人士:仍然清洁高效的缺点:你重新驾驭车轮

大师的方式:使用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"
Run Code Online (Sandbox Code Playgroud)

专业人士:你会感受到黑暗权力的缺点:那些会读你代码的人可能会开始不喜欢你

  • 为古茹方式+1(不好,无论如何都很好的答案,但真的很喜欢古茹方式的利弊) (2认同)