English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python 基础教程

Python 流程控制

Fonctions en Python

Types de données en Python

Python 文件操作

Python 对象和类

Python 日期和时间

Python 高级知识

Python 参考手册

Python 程序将两个矩阵相乘

Complete Python Examples

在此示例中,我们将学习使用两种不同的方法来乘法矩阵:嵌套循环和嵌套列表理解

要理解此示例,您应该了解以下Python编程主题:

在Python中,我们可以将矩阵实现为嵌套列表(列表内的列表)。

我们可以将每个元素视为矩阵的一行。

例如X = [[1, 2], [4, 5], [3, 63x2Matrice.

La première ligne peut être choisie comme X[0]. De plus, l'élément de la première ligne et de la première colonne peut être sélectionné comme X[0][0].

Seulement lorsque le nombre de colonnes de X est égal au nombre de lignes de Y, la multiplication des deux matrices X et Y est définie.

If X is an n x m matrix and Y is an m x l matrix, then XY is defined, with dimensions n x l (but YX is not defined). Here are several methods to implement matrix multiplication in Python.

Source code: Matrix multiplication using nested loops

# Program to multiply two matrices using nested loops
# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]
# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]
# Result is 3x4
result = [[0,0,0,0],
         [0,0,0,0],
         [0,0,0,0]]
# Traverse X rows
for i in range(len(X)):
   # Traverse Y columns
   for j in range(len(Y[0])):
       # Traverse Y rows
       for k in range(len(Y)):
           result[i][j] += X[i][k] * Y[k][j]
for r in result:
   print(r)

Output result

[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

In this program, we use nested for loops to traverse each row and column. We accumulate the sum of the products in the result.

This technique is simple, but as we increase the order of the matrix, the amount of computation is very large.

For larger matrix operations, we recommend using optimized software packages such asNumPyIt is several times faster than the above code (about1000 times).

Source code: Matrix multiplication using nested list comprehension

# Program to multiply two matrices using list comprehension
# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]
# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]
# Result is 3x4
result = [[sum(a*b for a, b in zip(X_row, Y_col)) for Y_col in zip(*Y)] for X_row in X]
for r in result:
   print(r)

The output of this program is the same as the one above. To understand the code above, we must first understand the built-in function zip() and use*Unpack the parameter list using operators.

We use nested lists to traverse each element in the matrix immediately. The code initially looks complex and unreadable. But once you master the list comprehension technique, you may not want to use nested loops anymore.

Complete Python Examples