📜  Python|删除元组中的重复列表(保留顺序)

📅  最后修改于: 2022-05-13 01:54:48.282000             🧑  作者: Mango

Python|删除元组中的重复列表(保留顺序)

有时,在处理记录时,我们可能会遇到需要删除重复记录的问题。这种问题在Web开发领域很常见。让我们讨论可以执行此任务的某些方式。
方法 #1:使用列表理解 + set()
在这种方法中,我们在每个列表出现时对其进行测试并将其添加到集合中,以避免重复出现,然后将其添加到新维护的唯一元组中,删除重复项。

Python3
# Python3 code to demonstrate working of
# Remove duplicate lists in tuples(Preserving Order)
# Using list comprehension + set()
 
# Initializing tuple
test_tup = ([4, 7, 8], [1, 2, 3], [4, 7, 8], [9, 10, 11], [1, 2, 3])
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Remove duplicate lists in tuples(Preserving Order)
# Using list comprehension + set()
temp = set()
res = [ele for ele in test_tup if not(tuple(ele) in temp or temp.add(tuple(ele)))]
 
# printing result
print("The unique lists tuple is : " + str(res))


Python3
# Python3 code to demonstrate working of
# Remove duplicate lists in tuples(Preserving Order)
# Using OrderedDict() + tuple()
from collections import OrderedDict
 
# Initializing tuple
test_tup = ([4, 7, 8], [1, 2, 3], [4, 7, 8], [9, 10, 11], [1, 2, 3])
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Remove duplicate lists in tuples(Preserving Order)
# Using OrderedDict() + tuple()
res = list(OrderedDict((tuple(x), x) for x in test_tup).values())
 
# printing result
print("The unique lists tuple is : " + str(res))


输出 :
The original tuple is : ([4, 7, 8], [1, 2, 3], [4, 7, 8], [9, 10, 11], [1, 2, 3])
The unique lists tuple is : [[4, 7, 8], [1, 2, 3], [9, 10, 11]]


方法#2:使用 OrderedDict() + tuple()
上述功能的组合也可用于执行此特定任务。在此,我们将元组转换为 OrderedDict(),它会自动删除重复的元素,然后使用 tuple() 构造一个新的元组列表。

Python3

# Python3 code to demonstrate working of
# Remove duplicate lists in tuples(Preserving Order)
# Using OrderedDict() + tuple()
from collections import OrderedDict
 
# Initializing tuple
test_tup = ([4, 7, 8], [1, 2, 3], [4, 7, 8], [9, 10, 11], [1, 2, 3])
 
# printing original tuple
print("The original tuple is : " + str(test_tup))
 
# Remove duplicate lists in tuples(Preserving Order)
# Using OrderedDict() + tuple()
res = list(OrderedDict((tuple(x), x) for x in test_tup).values())
 
# printing result
print("The unique lists tuple is : " + str(res))
输出 :
The original tuple is : ([4, 7, 8], [1, 2, 3], [4, 7, 8], [9, 10, 11], [1, 2, 3])
The unique lists tuple is : [[4, 7, 8], [1, 2, 3], [9, 10, 11]]