删除作为这些元组列表中列表的重复组合的元组 [英] Remove tuples that are duplicate combinations of lists in the list of these tuples
问题描述
我有清单
a = [([4, 7, 9], [3], 5.5), ([2, 5, 8], [3], 5.5), ([3], [4, 7, 9], 5.5), ([3], [2, 5, 8], 5.5)]
并且我正在尝试删除具有相同列表组合的重复元组.
and I am trying to remove duplicate tuples that have the same combination of lists.
例如([4,7,9],[3],5.5)
和([3],[4,7,9],5.5)
是相同的.因此,删除重复的元组后的输出将类似于:
For example, ([4, 7, 9], [3], 5.5)
and ([3], [4, 7, 9], 5.5)
are the same. So the output after removing the duplicate tuples will look something like:
a = [([4, 7, 9], [3], 5.5), ([2, 5, 8], [3], 5.5)]
允许以元组中的列表的任何顺序.
with any order of the lists in the tuples allowed.
编辑(基于@DYZ的反馈):不允许完全展平的元组.例如,不允许(4,7,9,3,5.5)
.输出应该仍然是以下形式:([list 1],[list2],常量)
.
Edit (based on @DYZ's feedback): Fully flattened tuples are not allowed. For example, (4,7,9,3,5.5)
is not allowed. The output should still be of the form: ([list 1], [list2], constant)
.
我尝试采用与相关的方法重复列表在Python中的列表中,但我陷入了精神僵局.
I tried to adapt a method that is related in Remove duplicated lists in list of lists in Python, but I have reached a mental deadlock..
是否可以在链接的问题中进一步修改代码,或者有更有效的方法吗?
Is it possible to modify the code further in the linked question, or is there a more efficient way to do this?
推荐答案
您可以为此工作使用字典.创建一个空字典:
You can use a dictionary for this job. Create an empty dictionary:
from itertools import chain
d = {}
将每个元组及其展平的形式分别作为值和键插入到字典中:
Insert each tuple and its flattened form into the dictionary as the value and the key, respectively:
for t in a:
# Flatten the tuple
flat = chain.from_iterable(part if isinstance(part,list) else [part]
for part in t)
maps_to = frozenset(flat) # Sets cannot be used as keys
d[maps_to] = t # Add it to the dict; the most recent addition "survives"
list(d.values())
#[([3], [4, 7, 9], 5.5), ([3], [2, 5, 8], 5.5)]
这篇关于删除作为这些元组列表中列表的重复组合的元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!