遍历列
如何循环遍历二维数组中的每一列?
为了遍历每一列,只需遍历转置矩阵(a transposed matrix is just a new matrix where the rows of original matrix are now columns and vice-versa)。
# zip(*matrix) generates a transposed version of your matrix
for column in zip(*matrix):
do_something(column)
对您提出的问题/示例的回答
我想做一个方法来检查是否至少有一列
在二维数组中该列具有相同的值
一般方法:
def check(matrix):
for column in zip(*matrix):
if column[1:] == column[:-1]:
return True
return False
单线:
arr = [[2,0,3],[4,2,3],[1,0,3]]
any([x[1:] == x[:-1] for x in zip(*arr)])
解释:
arr = [[2,0,3],[4,2,3],[1,0,3]]
# transpose the matrix
transposed = zip(*arr) # transposed = [(2, 4, 1), (0, 2, 0), (3, 3, 3)]
# x[1:] == x[:-1] is a trick.
# It checks if the subarrays {one of them by removing the first element (x[1:])
# and the other one by removing the last element (x[:-1])} are equals.
# They will be identical if all the elements are equal.
equals = [x[1:] == x[:-1] for x in transposed] # equals = [False, False, True]
# verify if at least one element of 'equals' is True
any(equals) # True
更新 01
@BenC 写道:
"您也可以跳过列表推导周围的 [],以便任何
只是得到一个可以提前停止一次的生成器/如果它返回
假”
所以:
arr = [[2,0,3],[4,2,3],[1,0,3]]
any(x[1:] == x[:-1] for x in zip(*arr))
更新 02
您也可以使用集合(与@HelloV 的答案合并)。
单线:
arr = [[2,0,3],[4,2,3],[1,0,3]]
any(len(set(x))==1 for x in zip(*arr))
一般方法:
def check(matrix):
for column in zip(*matrix):
if len(set(column)) == 1:
return True
return False
一个集合没有重复的元素,所以如果你将一个列表转换成一个集合set(x),任何重复的元素都会消失,所以,如果所有元素都相等,那么结果集合的长度等于一个len(set(x))==1。