gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:32:32 24 4
gpt4 key购买 nike

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

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 循环和 reinitialize开始处理新列时的结果。

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 thefunction? 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]

关于python - 在不使用 numpy 的情况下查找矩阵中所有行的列总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64956770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com