我正在编写一个代码来确定我的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
使用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
Run Code Online (Sandbox Code Playgroud)
另一种方法是将所有内容包装在函数中并用于return
从循环中逃脱.
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)
优点:易于理解缺点:每个循环的附加条件语句
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
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)
专业人士:你会感受到黑暗权力的缺点:那些会读你代码的人可能会开始不喜欢你