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

时间:2018-11-29 20:50:48

标签: python loops matrix multidimensional-array sum

所以我有一个Python程序,可以创建3 x 3矩阵(不使用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函数进行打印时,它将分别打印矩阵的每一行的总和?

1 个答案:

答案 0 :(得分:1)

给出如下矩阵:

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