Python 在向用户收集矩阵元素的情况下,如何获得两个矩阵相加的结果

Python 在向用户收集矩阵元素的情况下,如何获得两个矩阵相加的结果,python,Python,从用户处获取元素作为输入,并添加两个矩阵 B3=int(input("Enter the number of rows ")) B4=int(input("Enter the number of columns ")) Row1=[] for i in range(B3): m1=[] for j in range(B4): m1.append(input("num

从用户处获取元素作为输入,并添加两个矩阵

 B3=int(input("Enter the number of rows "))
        B4=int(input("Enter the number of columns "))
        Row1=[]
        for i in range(B3):
            m1=[]
            for j in range(B4):
                m1.append(input("num "))
            Row1.append(m1)
    #Printing the first Matrix
        print(Row1)
        print(len(Row1[0]))
        print(len(Row1))
        Row2=[]
        for i in range(B3):
            n1=[]
            for j in range(B4):
                n1.append(input("num "))
            Row2.append(n1)
    #Printing the second Matrix
        print(Row2)
        Result=[]
        for i in range(len(Row1)):
            for j in range(len(Row1[0])):
                Result[i][j]=Row1[i][j]+Row2[i][j]
    #Printing the addition result of the two matrices
        for r in result:
           print(r)
#

#getting elements as input from user and adding the two matrices.    
#B3 and B4 are the rows and columns of the each matrix 
        B3=int(input("Enter the number of rows "))
        B4=int(input("Enter the number of columns "))
        Row1=[]
        for i in range(B3):
            m1=[]
            for j in range(B4):
                m1.append(input("num "))
            Row1.append(m1)
    #Printing the first Matrix
        print(Row1)
        print(len(Row1[0]))
        print(len(Row1))
        Row2=[]
        for i in range(B3):
            n1=[]
            for j in range(B4):
                n1.append(input("num "))
            Row2.append(n1)
    #Printing the second Matrix
        print(Row2)
        Result=[]
        for i in range(len(Row1)):
            for j in range(len(Row1[0])):
                Result[i][j]=Row1[i][j]+Row2[i][j]
    #Printing the addition result of the two matrices
        for r in result:
           print(r)
我作为索引器出错:列表索引超出范围。请帮助解决此问题。我想将元素作为用户的输入添加到矩阵中,然后打印两个矩阵的加法。两个矩阵相加的代码块出错。

索引超出范围错误 您的错误在
结果[i][j]=Row1[i][j]+Row2[i][j]
行中。让我们看看:

Result=[]
for i in range(len(Row1)):
    for j in range(len(Row1[0])):
        Result[i][j]=Row1[i][j]+Row2[i][j]
Result
是一个空列表。当您尝试访问它时(
Result[i][j]
),索引超出范围

正确的方法是:

Result=[]
for i in range(len(Row1)):
    row = []
    for j in range(len(Row1[0])):
         row.append(Row1[i][j]+Row2[i][j])
    Result.append(row)
与您在代码的其他部分中使用的相同技巧

小事 在result:中为r添加了
,这应该是result:
中为r添加的
(大写字母,您之前定义了这样的名称)

最后,您从未将字符串转换为数字。sum运算符只是连接字符串,因此您使用的是
'1'+'1'='11'
而不是
1+1=2
。要解决此问题,您需要转换所有条目,如

m1.append(input("num "))
进入:

如果要使用整数,或:

m1.append(float(input("num ")))
允许浮点数

m1.append(float(input("num ")))