python - Getting unique tuples from a list -


this question has answer here:

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

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -