Python|从元组列表中删除重复的元组
给定一个元组列表,编写一个Python程序从给定列表中删除所有重复的元组。
例子:
Input : [(1, 2), (5, 7), (3, 6), (1, 2)]
Output : [(1, 2), (5, 7), (3, 6)]
Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')]
Output : [('a', 'z'), ('a', 'x'), ('z', 'x')]
方法#1:列表理解
这是使用列表理解的一种天真的方法。在这里,我们使用两个for循环并设置数据结构来取消所有重复项。
# Python3 program to remove duplicate
# tuples from list of tuples
def removeDuplicates(lst):
return [t for t in (set(tuple(i) for i in lst))]
# Driver code
lst = [(1, 2), (5, 7), (3, 6), (1, 2)]
print(removeDuplicates(lst))
输出:
[(1, 2), (5, 7), (3, 6)]
方法#2:列表理解(有效方法)
与上述方法相比,此方法效率更高,这里我们在列表推导中使用单个 for 循环,然后将其转换为 set 以删除重复项,然后再次将其转换为列表。
# Python3 program to remove duplicate
# tuples from list of tuples
def removeDuplicates(lst):
return list(set([i for i in lst]))
# Driver code
lst = [(1, 2), (5, 7), (3, 6), (1, 2)]
print(removeDuplicates(lst))
输出:
[(1, 2), (5, 7), (3, 6)]
方法#3: Python enumerate()方法
# Python3 program to remove duplicate
# tuples from list of tuples
def removeDuplicates(lst):
return [[a, b] for i, [a, b] in enumerate(lst)
if not any(c == b for _, c in lst[:i])]
# Driver code
lst = [(1, 2), (5, 7), (3, 6), (1, 2)]
print(removeDuplicates(lst))
输出:
[[1, 2], [5, 7], [3, 6]]