Python – 删除元组中的第 K 个索引重复项
有时,在处理Python记录时,我们可能会遇到需要删除所有元组的问题,这些元组在记录列表中具有相似的第 K 个索引元素。这种问题在日常和Web开发领域很常见。让我们讨论可以执行此任务的某些方式。
Input : test_list = [(4, 5, 6), (2, 3, 4), (1, 3, 4), (7, 6, 4), (1, 2, 6)], K = 1
Output : [(4, 5, 6), (2, 3, 4), (7, 6, 4), (1, 2, 6)]
Input : test_list = [(4, 5, 6), (2, 3, 4), (1, 3, 4), (7, 6, 4), (1, 2, 6)], K = 0
Output : [(4, 5, 6), (2, 3, 4), (1, 3, 4), (7, 6, 4)]
方法#1:使用循环
这是可以执行此任务的方式之一。在此,我们执行记忆集合中已经出现的第 K 个索引元素的任务,并每次检查新值。
# Python3 code to demonstrate working of
# Remove Kth Index Duplicates in Tuple
# Using loop
# initializing lists
test_list = [(4, 5, 6), (2, 3, 4), (1, 3, 4), (7, 6, 4), (1, 2, 6)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# Remove Kth Index Duplicates in Tuple
# Using loop
keep = set()
res = []
for sub in test_list:
if sub[K] not in keep:
res.append(sub)
keep.add(sub[K])
# printing result
print("Filtered Tuples : " + str(res))
输出 :
The original list is : [(4, 5, 6), (2, 3, 4), (1, 3, 4), (7, 6, 4), (1, 2, 6)]
Filtered Tuples : [(4, 5, 6), (2, 3, 4)]
方法 #2:使用groupby() + itemgetter()
+ 列表理解
上述功能的组合可以用来解决这个问题。在此,我们使用 itemgetter() 执行检查第 K 个元素的任务,并且 groupby() 用于形成组,我们通过访问第 0 个索引从中提取第一个元素。
# Python3 code to demonstrate working of
# Remove Kth Index Duplicates in Tuple
# Using groupby() + itemgetter() + list comprehension
from itertools import groupby
from operator import itemgetter
# initializing lists
test_list = [(4, 5, 6), (2, 3, 4), (1, 3, 4), (7, 6, 4), (1, 2, 6)]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# Remove Kth Index Duplicates in Tuple
# Using groupby() + itemgetter() + list comprehension
res = res = [list(val)[0] for key, val in groupby(sorted(test_list,
key = itemgetter(K)), key = itemgetter(K))]
# printing result
print("Filtered Tuples : " + str(res))
输出 :
The original list is : [(4, 5, 6), (2, 3, 4), (1, 3, 4), (7, 6, 4), (1, 2, 6)]
Filtered Tuples : [(4, 5, 6), (2, 3, 4)]