def matrixmulti(mat1,mat2):
result=[]
'''
for i in range(len(mat1)):
for j in range(len(mat2[0])):
for k in range(len(mat2)):
result[i][j] += mat1[i][k] * mat2[k][j]
print (result[i][j])
'''
result = [[sum(a * b for a, b in zip(mat1_row, mat2_col))
for mat2_col in zip(*mat2)]
for mat1_row in mat1]
for i in range(len(mat1)):
for j in range(len(mat2[0])):
print(mat[i][j],end=" ")
print()
我首先尝试使用嵌套的for循环,由于某种原因它没有执行,但是嵌套列表也发生了同样的事情。谁能帮助我我在哪里做错了什么?我刚刚通过了两个全局初始化的矩阵来传递函数。
您在代码中犯了很少的错误,可以修复该错误以使其正常工作。我已经制作了一个固定的三环版本,并在此处添加了一些注释,以说明如何正确完成它:
def matrixmulti(mat1,mat2):
# <-- code in functions needs to be indented in python for it to be considered inside the function!
if len(mat1[0]) != len(mat2): # Optional: check if "inner" dimensions match and throw an exception if they don't
raise ValueError("matrices dimensions does not match")
# initializing the result matrix to all zeroes. "_" means we don't care about the value of a variable
result = [ [ 0 for _ in range(len(mat1)) ] for _ in range(len(mat2[0])) ]
# doing the naive triple for-loop calculation
for i in range(len(mat1)):
for j in range(len(mat2[0])):
for k in range(len(mat2)):
result[i][j] += mat1[i][k] * mat2[k][j]
# don't forget to return the results! otherwise you function is not super helpful
return result
# heres the matrix printing wrapped up in a function
def print_matrix(matrix):
for i in range(len(matrix)):
for j in range(len(matrix[0])):
print(matrix[i][j],end=" ")
print()
multiplied = matrixmulti(mat1, mat2) # do the calculation and store the results in "multiplied"
print_matrix(multiplied) # finally print the results
您犯了几个错误:
matrixmulti
函数返回结果,或者在函数内部打印结果才能获得帮助希望这会有所帮助。