不分顺序删除重复元组的Python程序
给定一个二进制元组列表,任务是编写一个Python程序来删除所有重复的元组,而不考虑顺序,即如果包含相似的元素,则不考虑顺序删除。
Input : test_list = [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]
Output : [(1, 2), (5, 7), (4, 6), (2, 9)]
Explanation : (2, 1), (6, 4) are removed as (1, 2), (4, 6) are already included.
Input : test_list = [(4, 7), (1, 2), (9, 2), (2, 1), (5, 7), (7, 4), (9, 2)]
Output : [(1, 2), (5, 7), (4, 7), (2, 9)]
Explanation : (2, 1), (7, 4) are removed as (1, 2), (4, 7) are already included.
方法 1:使用map() 、 sorted() 、 set()和list()
在这里,我们使用 sorted() 和 map() 对 tuple 的每个元素进行排序。然后将结果转换为设置以删除重复项。最后,将集合转换为列表。
例子:
Python3
# initializing list
test_list = [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]
# printing original list
print("The original list is : " + str(test_list))
# using map() to get all sorted
# set removes duplicates
res = list({*map(tuple, map(sorted, test_list))})
# printing result
print("Tuples after removal : " + str(res))
Python3
# initializing list
test_list = [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]
# printing original list
print("The original list is : " + str(test_list))
# sorting tuples
temp = [tuple(sorted(sub)) for sub in test_list]
# removing duplicates
res = list(set(temp))
# printing result
print("Tuples after removal : " + str(res))
输出:
The original list is : [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]
Tuples after removal : [(2, 9), (1, 2), (4, 6), (5, 7)]
方法 2:使用列表理解, sorted()和set()
对于所需的解决方案,这是一种幼稚的方法。在这种情况下,列表的每个元素都使用列表理解和 sorted() 进行排序,然后使用 set() 将结果转换回以删除重复项。
例子:
蟒蛇3
# initializing list
test_list = [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]
# printing original list
print("The original list is : " + str(test_list))
# sorting tuples
temp = [tuple(sorted(sub)) for sub in test_list]
# removing duplicates
res = list(set(temp))
# printing result
print("Tuples after removal : " + str(res))
输出:
The original list is : [(4, 6), (1, 2), (9, 2), (2, 1), (5, 7), (6, 4), (9, 2)]
Tuples after removal : [(2, 9), (1, 2), (4, 6), (5, 7)]