有几种方法可以做到这一点:
简单方法:哨兵变量
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
优点:易于理解缺点:每个循环都有附加的条件语句
hacky方式:引发异常
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
优点:非常简单缺点:您在其语义之外使用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"
优点:更清洁且效率更高缺点:但感觉像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"
优点:仍然干净高效缺点:你重新发明了轮子
上师方式:使用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"
优点:您会感到拥有黑暗力量缺点:会读你代码的人可能开始不喜欢你