在 Python 中,我们可以将矩阵实现为嵌套列表(列表中的列表)。我们可以将每个元素视为矩阵的一行。
例如,`X = [[1, 2], [4, 5], [3, 6]]` 将表示一个 3x2 矩阵。第一行可以选择为 `X[0]`,第一行第一列的元素可以选择为 `X[0][0]`。
我们可以在 Python 中通过多种方式执行矩阵加法。以下是其中几种方式。
源代码:使用嵌套循环进行矩阵加法
# Program to add two matrices using nested loop
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)
输出
[17, 15, 4] [10, 12, 9] [11, 13, 18]
在此程序中,我们使用了嵌套的 `for` 循环来遍历每一行和每一列。在每一点,我们都将两个矩阵中对应的元素相加并将其存储在结果中。
源代码:使用嵌套列表推导式进行矩阵加法
# Program to add two matrices using list comprehension
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
result = [[X[i][j] + Y[i][j] for j in range(len(X[0]))] for i in range(len(X))]
for r in result:
print(r)
此程序的输出与上述相同。我们使用了嵌套列表推导式来遍历矩阵中的每个元素。
列表推导式允许我们编写简洁的代码,我们必须尝试在 Python 中经常使用它们。它们非常有用。
要了解更多信息,请访问 Python 列表推导式。
另请阅读