卡在 python 中的矩阵加法

Stuck with Matrix addition in python

请查看我在python中的矩阵加法代码并帮助我解决问题。

代码:

def matrix_addition(a, b):
# your code here
res = []  
for i in range(len(a)):
    for j in range(len(b)):
        sum = a[i][j] + b[i][j]
        res.append(sum)
return res

matrix_addition( [ [1, 2],[1, 2] ], [ [2, 3],[2, 3] ] )

预期输出:[[3, 5], [3, 5]]

我的输出:[3, 5, 3, 5]

如何初始化嵌套列表并在其中添加一些变量?

PS:我是 Python 的初学者,所以期待更简单的解决方案:)

对于 Python 的初学者,请特别注意缩进,因为它是 Python 语法的基础,没有像大多数 languages/scripts.

那样的结束分隔符

您没有为 sum 创建数组,也没有将它追加到正确的循环中。试试这个:

def matrix_addition(a, b):
# your code here
res = []  
for i in range(len(a)):
    sum = []
    for j in range(len(b)):
        sum.append([i][j] + b[i][j])
    res.append(sum)
return res