矩阵相乘

def matrixMul(matrix1, matrix2):
    if (len(matrix1[0]) != len(matrix2)):
        return False
    final = [[0 for j in range(len(matrix2[0]))] for i in range(len(matrix1))]
    for i in range(len(matrix1)):
        for j in range(len(matrix2[0])):
            for z in range(len(matrix2)):
                final[i][j] += matrix1[i][z]*matrix2[z][j]
    return final
    
def matrixMul2(matrix1, matrix2):
    if (len(matrix1[0]) != len(matrix2)):
        return False
    return [[sum(a*b for a,b in zip(a,b)) for b in zip(*matrix2)]for a in matrix1]

x = [[1,2,3],[4,5,6]]
y = [[1,2,3,4,5],[0,0,1,1,1],[3,4,5,6,7]]
print (matrixMul2(x,y))

 

posted @ 2018-12-12 11:08  jiu~  阅读(187)  评论(0编辑  收藏  举报