Python – 删除 Equilength 和 Equisum 元组重复项
有时,在使用Python元组时,我们可能会遇到需要在等长和等和的基础上删除重复项的问题。这种问题也可以被打破以适应任何一个所需的条件。这种问题可能发生在数据域和日常编程中。让我们讨论可以执行此任务的某些方式。
Input : test_list = [(1, 2, 0), (3, 0), (2, 1)]
Output : [(1, 2, 0), (3, 0)]
Input : test_list = [(1, 2, 0), (3, 0, 0), (0, 2, 1)]
Output : [(1, 2, 0)]
方法#1:使用嵌套循环
这是可以执行此任务的方式之一。这是蛮力方法,我们为每个元组循环,匹配元组的大小和总和,并执行删除。
Python3
# Python3 code to demonstrate working of
# Remove Equilength and Equisum Tuple Duplicates
# Using nested loop
# initializing lists
test_list = [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
# printing original list
print("The original list is : " + str(test_list))
# Remove Equilength and Equisum Tuple Duplicates
# Using nested loop
res = []
for sub in test_list:
for sub1 in res:
if len(sub) == len(sub1) and sum(sub) == sum(sub1):
break
else:
res.append(sub)
# printing result
print("Tuples after filtration : " + str(res))
Python3
# Python3 code to demonstrate working of
# Remove Equilength and Equisum Tuple Duplicates
# Using dict() + values()
# initializing lists
test_list = [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
# printing original list
print("The original list is : " + str(test_list))
# Remove Equilength and Equisum Tuple Duplicates
# Using dict() + values()
res = list({(len(sub), sum(sub)): sub for sub in test_list}.values())
# printing result
print("Tuples after filtration : " + str(res))
输出
The original list is : [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
Tuples after filtration : [(4, 5, 6), (3, 0), (1, 2, 3)]
方法 #2:使用 dict() + values()
上述功能的组合提供了解决此问题的另一种方法。在此,我们只是利用具有唯一键的字典的属性,并使用 len 和元组之和创建一个元组键。因此,避免了重复。
Python3
# Python3 code to demonstrate working of
# Remove Equilength and Equisum Tuple Duplicates
# Using dict() + values()
# initializing lists
test_list = [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
# printing original list
print("The original list is : " + str(test_list))
# Remove Equilength and Equisum Tuple Duplicates
# Using dict() + values()
res = list({(len(sub), sum(sub)): sub for sub in test_list}.values())
# printing result
print("Tuples after filtration : " + str(res))
输出
The original list is : [(4, 5, 6), (3, 0), (2, 1), (1, 2, 3), (5, 5, 5)]
Tuples after filtration : [(5, 5, 5), (2, 1), (1, 2, 3)]