Need an easy way to remove duplicate nested tuples in python

I am currently working with a script that has lists that look like this:

example = [ ((2,1),(0,1)), ((0,1),(2,1)), ((2,1),(0,1)) ] 

Now return this list to the set:

 set( [ ((2,1),(0,1)), ((0,1),(2,1)) ] ) 

For my purposes, I need to recognize these tuples as equal. I don’t care about saving the order. All the decisions that I can think of are really messy, so if anyone has any ideas, I would be grateful.

+4
source share
3 answers
 In [10]: set(tuple(sorted(elt)) for elt in example) Out[10]: set([ ((0, 1), (2, 1)) ]) 
+5
source

It looks like you can use frisonates instead of tuples.

 >>> x = [((2, 1), (0, 1)), ((0, 1), (2, 1)), ((2, 1), (0, 1))] >>> x [((2, 1), (0, 1)), ((0, 1), (2, 1)), ((2, 1), (0, 1))] >>> set(frozenset(ts) for ts in x) set([frozenset([(0, 1), (2, 1)])]) 
+6
source

Convert all elements to sets first. Then create a set from the entire list.

0
source

All Articles