python - 如何停止 for 循环

标签 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-

如果 L[i][j]!==n 我想停止这个循环并返回 false。否则返回真。我将如何实现?

最佳答案

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

关于python - 如何停止 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6346492/

相关文章:

python - Groupby cumsum 设置为零并在值低于零时重新启动 cumsum

python - 计算点的整个 GeoDataFrame 的质心

python - 自动将 matplotlib basemap 置于数据中心

java - java中相当于python中的time.clock的是什么?

python - 将递归函数变成迭代函数

python - 如何使用 SQL 参数

Python SerialException : Device reports readiness to read but returned no data (device disconnected? )

python - 使用 pandas 从特定工作表中读取 x 列中的值

python - 如何将后面所有值的某些值移动到另一列

python - scikit-learn 中 PCA 的质量