我知道如何计算行的总和,如下所示: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)
关于python - 求 python 矩阵中某一列的总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43553870/