Python 不使用numpy查找矩阵中所有行的列之和
这是我的代码,用于查找给定矩阵中所有列的所有元素之和:Python 不使用numpy查找矩阵中所有行的列之和,python,list,matrix,2d,Python,List,Matrix,2d,这是我的代码,用于查找给定矩阵中所有列的所有元素之和: 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以获得其他列的
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,然后调用函数?我认为它被称为递归。我不知道我是编程新手您应该为j
使用另一个for循环,并在开始处理新列时重新初始化结果
for j in range(col):
result = 0
for i in range(row):
result += mat1[i][j]
print(result)
我可以在函数中插入代码吗?在得到第一列的答案后,我可以在循环外增加j,然后调用
功能?我认为它被称为递归
是的,你可以用递归来实现
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)]
在获取用户输入时出现问题,我在回答中提到并修复了该问题。谢谢!我终于知道怎么做了。