Grab unique tuples in python list, regardless of order

I have a python list:

[ (2,2),(2,3),(1,4),(2,2), etc...]

I need some kind of function that reduces it to its unique components ... which would be in the above list:

[ (2,2),(2,3),(1,4) ]

numpy unique does not do this. I can figure out how to do this - convert your tuples into numbers, [22,23,14,etc.]find the uniqueness and come back from there ... but I don’t know if the complexity will get complicated. Is there a function that will do what I'm trying to do with tuples?


Here is sample code that demonstrates the problem:

 import numpy as np

 x = [(2,2),(2,2),(2,3)]
 y = np.unique(x)

returns: y: [2 3]

And here is the implementation of the solution that the fix demonstrates:

 x = [(2,2),(2,2),(2,3)]
 y = list(set(x))

returns y: [(2,2), (2,3)]

+4
source share
3

, ( ) :

>>> l = [(2,2),(2,3),(1,4),(2,2)]
>>> list(set(l))
[(2, 3), (1, 4), (2, 2)]

, :

>>> seen = set()
>>> result = []
>>> for item in l:
...     if item not in seen:
...         seen.add(item)
...         result.append(item)
... 
>>> result
[(2, 2), (2, 3), (1, 4)]

, , OrderedDict :

>>> from collections import OrderedDict
>>> OrderedDict.fromkeys(l).keys()
[(2, 2), (2, 3), (1, 4)]
+16

set , list:

>>> list(set([ (2,2),(2,3),(1,4),(2,2) ]))
[(2, 3), (1, 4), (2, 2)]
+6

set() , :

unique = list(set(mylist))

set(), , . , , , :

unique = [v for i,v in enumerate(mylist) if v not in mylist[:i]]

, :

unique = []
for tup in mylist:
    if tup not in unique:
        unique.append(tup)
+3
source

All Articles