I have a list of sets :
L = [set([1, 4]), set([1, 4]), set([1, 2]), set([1, 2]), set([2, 4]), set([2, 4]), set([5, 6]), set([5, 6]), set([3, 6]), set([3, 6]), set([3, 5]), set([3, 5])]
(actually in my case a conversion of a list of reciprocal tuples)
and I want to remove duplicates to get :
L = [set([1, 4]), set([1, 2]), set([2, 4]), set([5, 6]), set([3, 6]), set([3, 5])]
But if I try :
>>> list(set(L))
TypeError: unhashable type: 'set'
Or
>>> list(np.unique(L))
TypeError: cannot compare sets using cmp()
How do I get a list of sets with distinct sets?
The best way is to convert your sets to
frozenset
s (which are hashable) and then useset
to get only the unique sets, like thisIf you want them as sets, then you can convert them back to
set
s like thisIf you want the order also to be maintained, while removing the duplicates, then you can use
collections.OrderedDict
, like thisHere is another alternative
There is another alternative.
An alternative using a loop: