use*_*316 7 python loops multidimensional-array
我已经看到了关于这个问题的答案,但没有人帮助我.有些人使用numpy,有些人使用其他平台来回答,这些平台可以帮助Python变得更简单.我不想要这些类型的东西,我想要简单的Python,而不需要导入库或其他任何东西.
让我们说:我想做一个方法来检查2D数组中是否至少有一列该列具有相同的值.例如:
arr = [[2,0,3],[4,2,3],[1,0,3]]
Run Code Online (Sandbox Code Playgroud)
发送arr到我的方法将返回,True因为在第三列中,每个术语中都有数字3.
我该怎么写这个方法?如何遍历2D阵列中的每一列?
如何遍历2D阵列中的每一列?
为了遍历每一列,只需循环遍历转置矩阵(转置矩阵只是一个新矩阵,其中原始矩阵的行现在是列,反之亦然).
# zip(*matrix) generates a transposed version of your matrix
for column in zip(*matrix):
do_something(column)
Run Code Online (Sandbox Code Playgroud)
我想做一个方法来检查2D数组中是否至少有一列列具有相同的值
一般方法:
def check(matrix):
for column in zip(*matrix):
if column[1:] == column[:-1]:
return True
return False
Run Code Online (Sandbox Code Playgroud)
一内胆:
arr = [[2,0,3],[4,2,3],[1,0,3]]
any([x[1:] == x[:-1] for x in zip(*arr)])
Run Code Online (Sandbox Code Playgroud)
说明:
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
Run Code Online (Sandbox Code Playgroud)
@BenC写道:
"你也可以跳过列表理解周围的[],这样任何只是得到一个可以提前停止的生成器/如果它返回false"
所以:
arr = [[2,0,3],[4,2,3],[1,0,3]]
any(x[1:] == x[:-1] for x in zip(*arr))
Run Code Online (Sandbox Code Playgroud)
你也可以使用集合(与@HelloV的答案合并).
一内胆:
arr = [[2,0,3],[4,2,3],[1,0,3]]
any(len(set(x))==1 for x in zip(*arr))
Run Code Online (Sandbox Code Playgroud)
一般方法:
def check(matrix):
for column in zip(*matrix):
if len(set(column)) == 1:
return True
return False
Run Code Online (Sandbox Code Playgroud)
集合没有重复的元素,因此如果将列表转换为集合,set(x)任何重复的元素都会消失,因此,如果所有元素都是等于,则结果集的长度等于1 len(set(x))==1.