python中的求和矩阵列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23145684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sum matrix columns in python
提问by vonbraun
I can sum the items in column zero fine. But where do I change the code to sum column 2, or 3, or 4 in the matrix? I'm easily stumped.
我可以对零列中的项目求和。但是我在哪里更改代码以对矩阵中的第 2、3 或 4 列求和?我很容易被难住。
def main():
matrix = []
for i in range(2):
s = input("Enter a 4-by-4 matrix row " + str(i) + ": ")
items = s.split() # Extracts items from the string
list = [ eval(x) for x in items ] # Convert items to numbers
matrix.append(list)
print("Sum of the elements in column 0 is", sumColumn(matrix))
def sumColumn(m):
for column in range(len(m[0])):
total = 0
for row in range(len(m)):
total += m[row][column]
return total
main()
采纳答案by user3286261
Here is your code changed to return the sum of whatever column you specify:
这是您的代码更改为返回您指定的任何列的总和:
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))
回答by inspectorG4dget
numpy could do this for you quite easily:
numpy 可以很容易地为你做到这一点:
def sumColumn(matrix):
return numpy.sum(matrix, axis=1) # axis=1 says "get the sum along the columns"
Of course, if you wanted do it by hand, here's how I would fix your code:
当然,如果您想手动完成,以下是我修复代码的方法:
def sumColumn(m):
answer = []
for column in range(len(m[0])):
t = 0
for row in m:
t += row[column]
answer.append(t)
return answer
Still, there is a simpler way, using zip:
不过,还有一种更简单的方法,使用 zip:
def sumColumn(m):
return [sum(col) for col in zip(*m)]
回答by michaelmeyer
This can be made easier if you represent the matrix as a flat array:
如果您将矩阵表示为平面数组,这会变得更容易:
m = [
1,2,3,4,
10,11,12,13,
100,101,102,103,
1001,1002,1003,1004
]
def sum_column(m, n):
return sum(m[i] for i in range(n, 4 * 4, 4))
回答by ChrisW
One-liner:
单线:
column_sums = [sum([row[i] for row in M]) for i in range(0,len(M[0]))]
also
还
row_sums = [sum(row) for row in M]
for any rectangular, non-empty matrix (list of lists) M
. e.g.
对于任何矩形的非空矩阵(列表列表)M
。例如
>>> M = [[1,2,3],\
>>> [4,5,6],\
>>> [7,8,9]]
>>>
>>> [sum([row[i] for row in M]) for i in range(0,len(M[0]))]
[12, 15, 18]
>>> [sum(row) for row in M]
[6, 15, 24]
回答by Vaka Chiranjeevi
To get the sum of all columns in the matrix you can use the below python numpy code:
要获得矩阵中所有列的总和,您可以使用以下 python numpy 代码:
matrixname.sum(axis=0)
回答by Fernando
import numpy as np
np.sum(M,axis=1)
where M is the matrix
其中 M 是矩阵