Python - 删除类似第 K 列元素的行
给定一个矩阵,如果相似元素出现在第 K 列的上方行中,则删除行。
Input : test_list = [[3, 4, 5], [2, 3, 5], [10, 4, 3], [7, 8, 9], [9, 3, 6]], K = 2
Output : [[3, 4, 5], [10, 4, 3], [7, 8, 9], [9, 3, 6]]
Explanation : In [2, 3, 5], we already has list [3, 4, 5] having 5 at K, i.e 2nd pos.
Input : test_list = [[3, 4, 5], [2, 3, 3], [10, 4, 3], [7, 8, 9], [9, 3, 6]], K = 2
Output : [[3, 4, 5], [2, 3, 3], [7, 8, 9], [9, 3, 6]]
Explanation : In [10, 4, 3], we already has list [2, 3, 3] having 3 at K, i.e 2nd pos.
方法:使用循环
在此,我们维护一个记忆容器,它跟踪第 K 列中的元素,如果行的第 K 列元素已经存在,则从结果中省略该行。
Python3
# Python3 code to demonstrate working of
# Remove Rows for similar Kth column element
# Using loop
# initializing list
test_list = [[3, 4, 5], [2, 3, 5], [10, 4, 3], [7, 8, 9], [9, 3, 6]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 1
res = []
memo = []
for sub in test_list:
# in operator used to check if present or not
if not sub[K] in memo:
res.append(sub)
memo.append(sub[K])
# printing result
print("The filtered Matrix : " + str(res))
输出
The original list is : [[3, 4, 5], [2, 3, 5], [10, 4, 3], [7, 8, 9], [9, 3, 6]]
The filtered Matrix : [[3, 4, 5], [2, 3, 5], [7, 8, 9]]