Python|从列表中获取唯一的元组
有时,在使用Python list 时,我们可能会遇到一个问题,我们需要找到 list 的唯一出现。拥有基本数据类型很容易处理,但有时,我们可能拥有复杂的数据类型,并且在这种情况下问题变得新。让我们讨论针对这个问题处理元组的某些方法。
方法 #1:使用list() + set()
与整数一样,它们是不可变的,它们也可以由set()
处理以删除重复项。它将列表转换为 set 并删除重复项并通过list()
转换回列表
# Python3 code to demonstrate working of
# Get unique tuples from list
# using set() + list()
# initializing list
test_list = [(4, 5), (6, 1), (4, 5), (6, 1)]
# printing original list
print("The original list is : " + str(test_list))
# Get unique tuples from list
# using set() + list()
res = list(set(test_list))
# printing result
print("List after removal of duplicates " + str(res))
输出 :
The original list is : [(4, 5), (6, 1), (4, 5), (6, 1)]
List after removal of duplicates [(4, 5), (6, 1)]
方法#2:使用dict.fromkeys() + list()
由于较新版本的Python字典,记住它们的插入顺序,列表内容可以转换为字典元素列表,它会记住顺序并删除重复项。它使用list()
转换回来。
# Python3 code to demonstrate working of
# Get unique tuples from list
# using dict.fromkeys() + list()
# initializing list
test_list = [(4, 5), (6, 1), (4, 5), (6, 1)]
# printing original list
print("The original list is : " + str(test_list))
# Get unique tuples from list
# using dict.fromkeys() + list()
res = list(dict.fromkeys(test_list))
# printing result
print("List after removal of duplicates " + str(res))
输出 :
The original list is : [(4, 5), (6, 1), (4, 5), (6, 1)]
List after removal of duplicates [(4, 5), (6, 1)]