我知道如何像这样计算一行的总和:row = [sum(row) for row in Matrix],但如何求 python 矩阵中一列的总和?
如果我有这个矩阵:
Matrix =[[0, 2, 2],
[0, 2, 2],
[0, 0, 2]]
它应该生成 3 个值,它们是:0、4 和 6。
请您参考如下方法:
看看 here 同样的问题,很棒的示例代码。看看
def sumColumn(m, column):
total = 0
for row in range(len(m)):
total += m[row][column]
return total
column = 1
print("Sum of the elements in column", column, "is", sumColumn(matrix, column))
您可以查看并每次向索引添加一个,以便您查看下一列
或者你可以使用 zip:
def sumColumn(m):
return [sum(col) for col in zip(*m)]
或来自 here 的更简单的方法:
sum(m[:,i]) for i in range(4)
