所以我有一个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函数打印时,它将分别打印矩阵每行的总和?在
假设矩阵如下:
可以通过索引(索引从0开始)到矩阵中来获取行:
^{pr2}$因为这只是一个列表,您可以对其调用
sum()
:相关问题 更多 >
编程相关推荐