Python程序添加两个矩阵

目标:编程计算两个矩阵的和,然后用Python打印。 例如:

null
Input : X= [[1,2,3],    [4 ,5,6],    [7 ,8,9]] Y = [[9,8,7],    [6,5,4],    [3,2,1]] Output : result= [[10,10,10],         [10,10,10],         [10,10,10]]

在Python中,我们可以通过以下方式执行矩阵加法。

  1. 使用 循环 :

python

# Program to add two matrices using nested loop
X = [[ 1 , 2 , 3 ],
[ 4 , 5 , 6 ],
[ 7 , 8 , 9 ]]
Y = [[ 9 , 8 , 7 ],
[ 6 , 5 , 4 ],
[ 3 , 2 , 1 ]]
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)


输出:

[10, 10, 10][10, 10, 10][10, 10, 10]

时间复杂性: O(len(X)*len(X[0]))

辅助空间: O(len(X)*len(X[0]))

另一种方法:

  1. 说明:- 在这个程序中,我们使用嵌套for循环遍历每一行和每一列。在每一点上,我们在两个矩阵中添加相应的元素,并将其存储在结果中。
  2. 使用嵌套 列表理解 : 在Python中,我们可以将矩阵实现为嵌套列表(列表中的列表)。我们可以把每个元素看作矩阵的一行。

python

# Program to add two matrices
# using list comprehension
X = [[ 1 , 2 , 3 ],
[ 4 , 5 , 6 ],
[ 7 , 8 , 9 ]]
Y = [[ 9 , 8 , 7 ],
[ 6 , 5 , 4 ],
[ 3 , 2 , 1 ]]
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)


输出:

[10, 10, 10][10, 10, 10][10, 10, 10]

另一种方法:

  1. 说明:- 该程序的输出与上述相同。我们使用嵌套列表理解来迭代矩阵中的每个元素。列表理解允许我们编写简洁的代码,我们必须尝试在Python中经常使用它们。他们很有帮助。
  2. 使用 zip() 和总和

python

# Program to add two matrices
# using zip()
X = [[ 1 , 2 , 3 ],
[ 4 , 5 , 6 ],
[ 7 , 8 , 9 ]]
Y = [[ 9 , 8 , 7 ],
[ 6 , 5 , 4 ],
[ 3 , 2 , 1 ]]
result = [ map ( sum , zip ( * t)) for t in zip (X, Y)]
print (result)


输出:

[[10, 10, 10], [10, 10, 10], [10, 10, 10]]

说明:- zip函数接受矩阵中每个元素(列表)的迭代器i,映射它们,使用sum()添加它们,并将它们存储在映射形式中。

本文由 ajay0007 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 贡献极客。组织 或者把你的文章寄到contribute@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。 如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写评论。。

© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享