函数,该函数返回Python中矩阵单行的元素之和

函数,该函数返回Python中矩阵单行的元素之和,python,loops,matrix,multidimensional-array,sum,Python,Loops,Matrix,Multidimensional Array,Sum,因此,我有一个Python程序,它创建了一个3x3矩阵,而不使用numPy。它包含一个函数,用于输入矩阵的元素,打印出来,并计算矩阵中单个行的总和。后者是我有问题的部分。如何编写getSumRow函数,使其返回矩阵中一行的元素之和。将矩阵和行索引传递给函数 #Program that creates a 3x3 matrix and prints sum of rows def getMatrix(): A=[[[] for i in range(3)] for i in ran

因此,我有一个Python程序,它创建了一个3x3矩阵,而不使用numPy。它包含一个函数,用于输入矩阵的元素,打印出来,并计算矩阵中单个行的总和。后者是我有问题的部分。如何编写getSumRow函数,使其返回矩阵中一行的元素之和。将矩阵和行索引传递给函数

#Program that creates a 3x3 matrix and prints sum of rows

   def getMatrix():
    A=[[[] for i in range(3)] for i in range(3)] #creating 2d list to store matrix
    for i in range(3): #setting column bounds to 3
        for j in range(3): #settting row bounds to 3
            number=int(input("Please Enter Elements of Matrix A:")) 
            A[i][j]=number #fills array using nested loops
    return A #returns 2d array (3x3 matrix)

def getSumRow(a,row):


def printMatrix(a):
    for i, element in enumerate(a): #where a is the 3x3 matrix
        print(*a[i])
    #accesses the 2d array and prints them in order of rows and columns

def main():
    #includes function calls 
    mat = getMatrix()
    print("The sum of row 1 is", getSumRow(mat,0))
    print("The sum of row 2 is", getSumRow(mat,1))
    print("The sum of row 3 is", getSumRow(mat,2))
    printMatrix(mat)

 main()
如何获取它,以便在使用getSumRow函数打印时,它将单独打印矩阵中每一行的总和?

给定如下矩阵:

matrix = [
    [1, 2, 6],
    [5, 8, 7],
    [9, 1, 2]
]
通过将从0开始的索引索引索引到矩阵中,可以获得一行:

matrix[1] # --> [5, 8, 7]
因为这只是一个列表,所以您可以在其上调用sum:

sum(matrix[1]) # --> 20

sum(matrix[2]) # --> 12