Python|根据第 K 个元素元组列表删除重复项
有时,在处理记录时,我们可能会遇到需要根据列表中元组的第 K 个元素删除重复项的问题。此问题适用于使用记录作为输入的域。让我们讨论一些可以解决这个问题的方法。
方法#1:使用循环
这是执行此特定任务的蛮力方法。在此,我们检查元组的第 K 个索引并添加到一个集合中以保持记录。如果该值已经在内存集中,我们将其从结果中丢弃,因为它是重复的。
# Python3 code to demonstrate working of
# Remove duplicates based on Kth element tuple list
# Using loop
# initialize list
test_list = [(3, 1, 5), (1, 3, 6), (2, 1, 7),
(5, 2, 8), (6, 3, 0)]
# printing original list
print("The original list is : " + str(test_list))
# initialize K
K = 1
# Remove duplicates based on Kth element tuple list
# Using loop
temp = set()
res = []
for ele in test_list:
if ele[K] not in temp:
res.append(ele)
temp.add(ele[K])
# printing result
print("The list after removal of K based duplicates : " + str(res))
输出 :
The original list is : [(3, 1, 5), (1, 3, 6), (2, 1, 7), (5, 2, 8), (6, 3, 0)]
The list after removal of K based duplicates : [(3, 1, 5), (1, 3, 6), (5, 2, 8)]
方法 #2:使用reduce() + lambda + keys()
在这种方法中,我们使用reduce() + lambda
执行过滤任务,并使用keys()
决定附加或不使用提取的键。如果 key 已经出现,则丢弃,否则添加。
# Python3 code to demonstrate working of
# Remove duplicates based on Kth element tuple list
# Using reduce() + lambda + keys()
from functools import reduce
# initialize list
test_list = [(3, 1), (1, 3), (3, 2), (5, 2), (5, 3)]
# printing original list
print("The original list is : " + str(test_list))
# initialize K
K = 0
# Remove duplicates based on Kth element tuple list
# Using reduce() + lambda + keys()
res = reduce(lambda sub, ele : ele[K] in dict(sub).keys()
and sub or sub + [ele], test_list, [])
# printing result
print("The list after removal of K based duplicates : " + str(res))
输出 :
The original list is : [(3, 1), (1, 3), (3, 2), (5, 2), (5, 3)]
The list after removal of K based duplicates : [(3, 1), (1, 3), (5, 2)]