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 easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList: List<String> al = new ArrayList<>(); // add elements to al, including duplicates Set<String> hs = new HashSet<>(); hs. addAll(al); al. clear(); al.
The best way is to convert your sets to frozenset
s (which are hashable) and then use set
to get only the unique sets, like this
>>> list(set(frozenset(item) for item in L))
[frozenset({2, 4}),
frozenset({3, 6}),
frozenset({1, 2}),
frozenset({5, 6}),
frozenset({1, 4}),
frozenset({3, 5})]
If you want them as sets, then you can convert them back to set
s like this
>>> [set(item) for item in set(frozenset(item) for item in L)]
[{2, 4}, {3, 6}, {1, 2}, {5, 6}, {1, 4}, {3, 5}]
If you want the order also to be maintained, while removing the duplicates, then you can use collections.OrderedDict
, like this
>>> from collections import OrderedDict
>>> [set(i) for i in OrderedDict.fromkeys(frozenset(item) for item in L)]
[{1, 4}, {1, 2}, {2, 4}, {5, 6}, {3, 6}, {3, 5}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With