卡在Matrix中

时间:2019-03-19 10:50:55

标签: python-3.x fundamentals-ts

请查看我在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的初学者,所以期待更简单的解决方案:)

1 个答案:

答案 0 :(得分:1)

对于使用Python的初学者,请特别注意缩进,因为缩进是Python语法的基础,没有像大多数语言/脚本一样的结尾定界符。

您没有为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