学习Python并陷入矩阵复用

2024-10-02 04:16:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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循环,由于某种原因它没有执行,但是嵌套列表也发生了同样的事情。 有人能帮我找出哪里做错了什么吗? 我刚刚传递了两个矩阵的函数,这两个矩阵是全局初始化的。你知道吗


Tags: inforlendefrange矩阵colresult
1条回答
网友
1楼 · 发布于 2024-10-02 04:16:43

你在代码中犯的错误很少,你可以通过修正来让它正常工作。 我已经制作了一个固定的三重循环版本,这里有一些注释来说明如何正确地执行它:

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

你犯了几个错误:

  1. 必须缩进函数代码,才能将其视为Python函数中的代码
  2. 如果要进行三重循环计算,则必须以某种方式初始化结果矩阵(在本例中,我使用列表理解进行初始化,以便获得正确的嵌套结构),否则,对结果矩阵的索引将失败,因为您试图访问不存在的嵌套部分
  3. 您必须返回来自matrixmulti函数的结果,或者在函数内部打印结果,这样它才有任何帮助

希望这有帮助。你知道吗

相关问题 更多 >

    热门问题