我正在编写一个代码来确定我的 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-
如果 L[i][j]!==n
我想停止这个循环并返回 false。否则返回真。我将如何实现?
最佳答案
使用 break
和 continue
来执行此操作。可以使用以下方法在 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
退出循环。
关于python - 如何停止 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6346492/