Q:python 3维矩阵乘法

def main():
    matrix1 = [ ]
    matrix2 = [ ]
    a = input("Please enter matrix 1:")
    a1 = a.split()
    for i in range(3):
        list = [eval(a1[j]) for j in range(i * 3, i * 3+3)]
        matrix1.append(list)

    b = input("Please enter matrix 2:")
    b1 = b.split()
    for i in range(3):
        list = [ eval(b1[j]) for j in range(i*3, i*3+3)]
        matrix2.append(list)
    g = multiplyMatrix(matrix1,matrix2)
    display(g)

def multiplyMatrix(a, b):
    c = [ ]
    list = len(b[0])*[0]
    for row in range(len(a)):
        #for col in range(len(b[0])):
        #    c[row].append([])                              '"""wrong ! why ?"""
        #___________________________________________________________________________
        #   File "matrix_mul.py", line 23, in multiplyMatrix c[row].append([])
        #   IndexError: list index out of range
IndexError: list index out of range

        c.append([x for x in list])
    for i in range(len(c)):
        for j in range(len(c[0])):
            for k in range(len(b)):
                c[i][j] += a[i][k] * b[k][j]
    return c
    
def display(matrix):
    for i in range(len(matrix)):
        for j in range(len(matrix[0])):
            print(format(matrix[i][j],".1f"),' ',end = '')
        print()
main()


你可能感兴趣的:(Q:python 3维矩阵乘法)