Reputation: 9869
I have a list similar to the following (which I have conveniently converted tuple of tuples of tuples so that set
can get the unique elements.
mylist = ((('pen','pineapple'),('apple','pen')),(('pineapple','pen')),(('apple','pen'),('pen','pineapple')))
set(mylist)
>>>
{(('pen', 'pineapple'), ('apple', 'pen')),
('pineapple', 'pen'),
(('apple', 'pen'), ('pen', 'pineapple'))}
However, the element ('apple', 'pen'), ('pen', 'pineapple') == ('pen', 'pineapple'), ('apple', 'pen')
as far as my application is concerned. Is there a quick python
method to get the unique elements disregarding order of elements.
Edit 1: As pointed out in comments:
(( 'pen', 'apple'), ('pen', 'pineapple')) != (('apple', 'pen'), ('pen', 'pineapple'))
. i.e. I do not want to rearrange the innermost tuples. However, it is ok to rearrange the middle level of tuples.
Btw I was hoping for something a bit pythonic (or fancier) than using sort and then using set
.
Upvotes: 1
Views: 309
Reputation: 298106
Make a set of sets. Sets can only contain immutable objects, so you'll have to convert every tuple into a frozenset
and then make a set out of it:
In [4]: set(map(frozenset, mylist))
Out[4]:
{frozenset({('apple', 'pen'), ('pen', 'pineapple')}),
frozenset({'pen', 'pineapple'})}
Upvotes: 4