【发布时间】: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