python - 求 python 矩阵中某一列的总和?

标签 python arrays python-2.7 matrix

我知道如何计算行的总和,如下所示:row = [sum(row) for row in Matrix],但是如何找到Python矩阵中的列的总和?

如果我有这个矩阵:

Matrix =[[0, 2, 2],
         [0, 2, 2], 
         [0, 0, 2]]

它应该产生 3 个值,它们是:046

最佳答案

看看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/

相关文章:

Python http服务器存储接收到的消息

java - 为什么重载方法选择的是 Object 而不是带有原始数组的 Object[] ?

c - 修改结构中的 char *

python - 缩进错误: unindent does not match any outer indentation level python

python - 计算一个数组的元素在另一个数组中的出现次数

python - 禁用、隐藏或删除 Tkinter 中的关闭 "X"按钮

Python 模块和 __all__

python - 在模板中显示和格式化 Django DurationField

c - 两个进程共享内存中的结构体数组

python - "pythonic"从文件中切片行列表的方法是什么?