Stoner
Stoner

Reputation: 906

Remove tuples that are duplicate combinations of lists in the list of these tuples

I have the list

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.

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.

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).

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?

Upvotes: 1

Views: 794

Answers (2)

kevinkayaks
kevinkayaks

Reputation: 2726

Sort the elements of a by their length (setting the length of elements which aren't list as -1). Then find the indices of the unique elements of the resulting sort, and use those to index into the unsorted list.

asort = [sorted(aa, key= lambda x: len(x) if isinstance(x,list) else -1) for aa in a]
inds = [i for i,x in enumerate(asort) if asort.index(x)==i]
a = [a[i] for i in inds]

Upvotes: 2

DYZ
DYZ

Reputation: 57075

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)]

Upvotes: 1

Related Questions