Python - 元素明智的矩阵差异
给定两个矩阵,任务是编写一个Python程序来执行元素差异。
例子:
Input : test_list1 = [[2, 4, 5], [5, 4, 2], [1, 2, 3]], test_list2 = [[6, 4, 6], [9, 6, 3], [7, 5, 4]]
Output : [[4, 0, 1], [4, 2, 1], [6, 3, 1]]
Explanation : 6 – 2 = 4, 4 – 4 = 0, 6 – 5 = 1. And so on.
Input : test_list1 = [[2, 4, 5], [1, 2, 3]], test_list2 = [[6, 4, 6], [7, 5, 4]]
Output : [[4, 0, 1], [6, 3, 1]]
Explanation : 6 – 2 = 4, 4 – 4 = 0, 6 – 5 = 1. And so on.
方法 #1:使用循环 + zip()
在这里,我们执行使用 zip 和嵌套循环在行和行内组合索引的任务,用于遍历所有行的所有元素。
Python3
# Python3 code to demonstrate working of
# Element-wise Matrix Difference
# Using loop + zip()
# initializing lists
test_list1 = [[2, 4, 5], [5, 4, 2], [1, 2, 3]]
test_list2 = [[6, 4, 6], [9, 6, 3], [7, 5, 4]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
res = []
# iterating for rows
for sub1, sub2 in zip(test_list1, test_list2):
temp = []
# interate for elements
for ele1, ele2 in zip(sub1, sub2):
temp.append(ele2 - ele1)
res.append(temp)
# printing result
print("The Matrix Difference : " + str(res))
Python3
# Python3 code to demonstrate working of
# Element-wise Matrix Difference
# Using loop + zip()
# initializing lists
test_list1 = [[2, 4, 5], [5, 4, 2], [1, 2, 3]]
test_list2 = [[6, 4, 6], [9, 6, 3], [7, 5, 4]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# using list comprehension to perform task in one line
res = [[ele2 - ele1 for ele1, ele2 in zip(sub1, sub2)]
for sub1, sub2 in zip(test_list1, test_list2)]
# printing result
print("The Matrix Difference : " + str(res))
输出
The original list 1 is : [[2, 4, 5], [5, 4, 2], [1, 2, 3]]
The original list 2 is : [[6, 4, 6], [9, 6, 3], [7, 5, 4]]
The Matrix Difference : [[4, 0, 1], [4, 2, 1], [6, 3, 1]]
方法 #2:使用列表理解+ zip()
在这里,我们使用 zip() 执行压缩任务,并且使用列表理解以一种线性方式解决这个问题。
蟒蛇3
# Python3 code to demonstrate working of
# Element-wise Matrix Difference
# Using loop + zip()
# initializing lists
test_list1 = [[2, 4, 5], [5, 4, 2], [1, 2, 3]]
test_list2 = [[6, 4, 6], [9, 6, 3], [7, 5, 4]]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# using list comprehension to perform task in one line
res = [[ele2 - ele1 for ele1, ele2 in zip(sub1, sub2)]
for sub1, sub2 in zip(test_list1, test_list2)]
# printing result
print("The Matrix Difference : " + str(res))
输出
The original list 1 is : [[2, 4, 5], [5, 4, 2], [1, 2, 3]]
The original list 2 is : [[6, 4, 6], [9, 6, 3], [7, 5, 4]]
The Matrix Difference : [[4, 0, 1], [4, 2, 1], [6, 3, 1]]