在Python中对矩阵列求和
我可以顺利地把第零列的数加起来。但是我该在哪里修改代码,以便把第二列、第三列或第四列的数加起来呢?我有点困惑。
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()
6 个回答
2
import numpy as np
np.sum(M,axis=1)
这里的 M 是一个矩阵。
2
要计算矩阵中所有列的总和,你可以使用下面的Python numpy代码:
matrixname.sum(axis=0)
8
一句话总结:
column_sums = [sum([row[i] for row in M]) for i in range(0,len(M[0]))]
另外
row_sums = [sum(row) for row in M]
适用于任何矩形的、非空的矩阵(也就是列表中的列表)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]
13
numpy可以很轻松地帮你做到这一点:
def sumColumn(matrix):
return numpy.sum(matrix, axis=1) # axis=1 says "get the sum along the columns"
当然,如果你想手动来做,这里是我会如何修改你的代码:
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
不过,还有一个更简单的方法,可以用zip来实现:
def sumColumn(m):
return [sum(col) for col in zip(*m)]
2
这里是你修改后的代码,可以返回你指定的任意列的总和:
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))