萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 矩陣乘法三種實現:純 Python、列表推導式、NumPy

1. 三層循環(教學版)

def matmul(A, B):
    rows, cols = len(A), len(B[0])
    res = [[0]*cols for _ in range(rows)]
    for i in range(rows):
        for j in range(cols):
            for k in range(len(B)):
                res[i][j] += A[i][k] * B[k][j]
    return res

2. 列表推導式 + zip(Pythonic)

def matmul2(A, B):
    return [[sum(a*b for a,b in zip(row, col)) for col in zip(*B)] for row in A]

3. NumPy 矩陣乘法(生產環境首選)

from numpy import dot, array
A = array([[1,2],[3,4],[5,6],[7,8]])
B = array([[1,2,3,4],[5,6,7,8]])
print(dot(A, B).tolist())
# [[11, 14, 17, 20], [23, 30, 37, 44], [35, 46, 57, 68], [47, 62, 77, 92]]

性能對比

實現100x100 矩陣耗時備註
三層循環~1.2s純 Python,極慢
列表推導式~0.8s略快,仍受限於解釋器
NumPy dot~0.001sC/Fortran 後端,向量化,快 1000x+

建議

  • 學習算法原理用版本 1。
  • 腳本快速原型、小矩陣用版本 2。
  • 科學計算、機器學習、大規模數據**必須**用 NumPy/SciPy。
copyright © 萬盛學電腦網 all rights reserved