如何停止for循环 [英] how to stop a for loop
问题描述
我正在编写代码来确定我的 nxn 列表中的每个元素是否都相同.即 [[0,0],[0,0]]
返回 true 但 [[[0,1],[0,0]]
将返回 false.我正在考虑编写一个代码,当它找到与第一个元素不同的元素时立即停止.即:
I'm writing a code to determine if every element in my nxn list is the same. i.e. [[0,0],[0,0]]
returns true but [[0,1],[0,0]]
will return false. I was thinking of writing a code that stops immediately when it finds an element that is not the same as the first element. 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,我想停止这个循环.否则返回真.我将如何实施这一点?
I would like to stop this loop if L[i][j]!==n
and return false. otherwise return true. How would I go about implementing this?
推荐答案
使用 break
和 continue
来做到这一点.可以使用以下命令在 Python 中打破嵌套循环:
Use break
and continue
to do this. Breaking nested loops can be done in Python using the following:
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
退出循环.
Another way is to wrap everything in a function and use return
to escape from the loop.
这篇关于如何停止for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!