Python程序在矩阵中查找连续行差异
给定一个矩阵,任务是编写一个Python程序,根据存在的元素执行与前一行的差异。
Input : test_list = [[5, 6, 3, 1], [7, 5, 3, 1], [3, 2], [7, 3, 3, 2], [2, 3], [9, 8, 1]]
Output : [[], [7], [2], [7], [], [8, 9, 1]]
Explanation : Comparing 1st and 2nd row, only 7 exists in 2nd row and not in 1st hence [7] is output.
Input : test_list = [[5, 6], [7, 5, 3, 1], [3, 4], [7], [2, 9], [9, 8, 1]]
Output : [[], [1, 3, 7], [4], [7], [9, 2], [8, 1]]
Explanation : Comparing 2nd and 3rd list, only 4 is present in 3rd list and not in 2nd, hence output.
示例:使用set.difference() +循环
在这里,保持了前一组,保持了前一组的轨迹以获得差异。这将从当前列表中删除已经存在于前一个列表中的所有元素。
Python3
# Python3 code to demonstrate working of
# Sucessive row difference in Matrix
# Using set.difference + loop
# initializing list
test_list = [[5, 6, 3, 1], [7, 5, 3, 1],
[3, 2], [7, 3, 3, 2],
[2, 3], [9, 8, 1]]
# printing original list
print("The original list is : " + str(test_list))
res = []
prev = set(test_list[0])
for ele in test_list:
# appending difference set diff with previous
# element
res.append(list(set(ele).difference(prev)))
# updating prev. for comparison
prev = set(ele)
# printing result
print("Sucessive Row difference : " + str(res))
输出:
The original list is : [[5, 6, 3, 1], [7, 5, 3, 1], [3, 2], [7, 3, 3, 2], [2, 3], [9, 8, 1]]
Sucessive Row difference : [[], [7], [2], [7], [], [8, 9, 1]]