I want to find the unique elements in A =[set([1,2]),set([1,2]), set([1])] in Python. I tried set(A); it didn't work. Is there any easy way to do it?
Asked
Active
Viewed 847 times
1
Martijn Pieters
- 963,270
- 265
- 3,804
- 3,187
pmjn6
- 187
- 2
- 13
1 Answers
4
Convert your sets to frozenset() objects:
set(frozenset(s) for s in A)
A frozenset() is an immutable set object, and more importantly, hashable. Thus it can be stored in a set().
Demo:
>>> A = [set([1,2]),set([1,2]), set([1])]
>>> set(frozenset(s) for s in A)
set([frozenset([1, 2]), frozenset([1])])
Martijn Pieters
- 963,270
- 265
- 3,804
- 3,187