python - Getting unique tuples from a list -
this question has answer here:
- getting unique tuples out of python set 3 answers
i have list of tuples elements this:
aa = [('a', 'b'), ('c', 'd'), ('b', 'a')]
i want treat ('a', 'b') , ('b', 'a')
same group , want extract unique tuples. output should this:
[('a', 'b'), ('c', 'd')]
how can achieve efficiently list consists of millions of such tuples?
convert frozenset
, hash, , retrieve:
in [193]: map(tuple, set(map(frozenset, aa))) # python2 out[193]: [('d', 'c'), ('a', 'b')]
here's more readable version list comprehension:
in [194]: [tuple(x) x in set(map(frozenset, aa))] out[194]: [('d', 'c'), ('a', 'b')]
do note that, particular use case, list of tuples isn't best choice of data structure. consider storing data set begin with?
in [477]: set(map(frozenset, aa)) out[477]: {frozenset({'a', 'b'}), frozenset({'c', 'd'})}
Comments
Post a Comment