💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# Python 程序:将两个矩阵相乘 > 原文: [https://www.programiz.com/python-programming/examples/multiply-matrix](https://www.programiz.com/python-programming/examples/multiply-matrix) #### 在此示例中,我们将学习使用两种不同的方法来乘法矩阵:嵌套循环和嵌套列表推导式 要理解此示例,您应该了解以下 [Python 编程](/python-programming "Python tutorial")主题: * [Python `for`循环](/python-programming/for-loop) * [Python 列表](/python-programming/list) * [Python 矩阵和 NumPy 数组](/python-programming/matrix) * * * 在 Python 中,我们可以将矩阵实现为嵌套列表(列表内的列表)。 我们可以将每个元素视为矩阵的一行。 例如,`X = [[1, 2], [4, 5], [3, 6]]`将代表`3x2`矩阵。 第一行可以选择为`X[0]`。 并且,可以将第一行第一列中的元素选择为`X[0][0]`。 仅当`X`中的列数等于`Y`行数时,才定义两个矩阵`X`和`Y`的相乘。 如果`X`是`n x m`矩阵,而`Y`是`m x l`矩阵,则定义`XY`并具有尺寸`n x l`(但`YX`未定义)。 以下是在 Python 中实现矩阵乘法的两种方法。 ### 源代码:使用嵌套循环的矩阵乘法 ```py # 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]] # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r) ``` **输出** ```py [114, 160, 60, 27] [74, 97, 73, 14] [119, 157, 112, 23] ``` 在此程序中,我们使用了嵌套的`for`循环来遍历每一行和每一列。 我们累加结果中的乘积之和。 这种技术很简单,但是随着我们增加矩阵的阶数,计算量很大。 对于较大的矩阵操作,我们建议使用优化的软件包,例如 [NumPy](http://www.numpy.org/ "NumPy Official Website") ,它比上述代码快几倍(大约 1000 倍)。 ### 源代码:使用嵌套列表推导式的矩阵乘法 ```py # 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) ``` 该程序的输出与上述相同。 要理解以上代码,我们必须首先了解使用*运算符的[内置函数`zip()`](http://docs.python.org/3/library/functions.html?highlight=zip#zip "built-in function zip") 和[解包参数列表](http://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists "unpacking argument list")的方法。 我们使用嵌套列表推导式来遍历矩阵中的每个元素。 该代码起初看起来很复杂且不可读。 但是一旦掌握了列表推导式的技巧,您可能就不会回到嵌套循环了。