【问题标题】:Function that returns the sum of the elements of a single row of a matrix in Python在Python中返回矩阵单行元素之和的函数
【发布时间】:2023-03-25 02:01:01
【问题描述】:

所以我有一个 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 函数打印时,它会单独打印矩阵每一行的总和?

【问题讨论】:

    标签: python loops matrix multidimensional-array sum


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-08
      相关资源
      最近更新 更多