在不使用numpy的情况下查找矩阵中所有行的列总和

Finding the sum of column of all the rows in a matrix without using numpy

这是我的代码,用于查找给定矩阵中所有列的所有元素的总和:

row, col = map(int, input().split())
mat1 = [list(map(int, input().split())) for i in range(row)]

result = 0

j = 0
for i in range(row):
    result += mat1[i][j]

print(result)

我能够得到第一列的答案,但我无法得到其他列的答案。我应该在哪里将 j 增加到 +1 以获得其他列的结果?

这是输入:

2 2
5 -1
19 8

这是输出:

24
7

我得到 24 作为答案。我现在应该如何获得7

编辑:

我可以在函数中插入代码吗?在我得到第一列的答案后,我可以在循环外递增 j 然后调用函数?我认为这被称为递归。我不知道我是编程新手

您应该为 jreinitialize 使用另一个 for 循环 result 当一个新的 开始处理。

for j in range(col):
   result = 0
   for i in range(row):
       result += mat1[i][j]
   print(result)

Can I insert the code in a function? After I got the first column's answer, I can increment j outside the loop and then call the function? I think it is known as recursion.

是的,你可以用递归来做到这一点。

matrix = [[5, -1], [19, 8]]
row = 2
column = 2

def getResult(j, matrix, result):
   if j >= column:
      return result
   s = sum([matrix[i][j] for i in range(row)])
   result.append(s)
   return getResult(j + 1, matrix, result)

result = getResult(0, matrix, [])

输出

> result
[24, 7]

您应该在列上定义循环(您使用了固定值 j)并为每一列调用您的代码,如下所示:

row, col = map(int, input().split())
mat1 = [list(map(int, input().split())) for i in range(row)]

def sum_column(mat1, row, j):
    result = 0 #initialize
    for i in range(row): #loop on rows
        result += mat1[i][j]
    return result

for j in range(col): #loop on columns
    #call function for each column
    print(f'Column {j +1} sum: {sum_column(mat1, row, j)}')

更新: 请注意您从用户那里获得输入的方式。尽管该函数应用于 col,但在您的代码中,用户可以定义比 col 更多的列。您可以像这样忽略额外的列:

mat1 = [list(map(int, input().split()[:col])) for i in range(row)]