我可以将第0列中的项目加总。但是我在哪里将代码更改为矩阵中的第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()
答案 0 :(得分:9)
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)]
答案 1 :(得分:4)
一衬垫:
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
。 e.g。
>>> 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]
答案 2 :(得分:1)
要获取矩阵中所有列的总和,可以使用以下python numpy代码:
matrixname.sum(axis=0)
答案 3 :(得分:0)
如果将矩阵表示为平面数组,这可以更容易:
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))
答案 4 :(得分:0)
以下代码已更改为返回指定列的总和:
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))
答案 5 :(得分:0)
import numpy as np
np.sum(M,axis=1)
其中M是矩阵