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 -

reflection - How to access the object-members of an object declaration in kotlin -

php - Doctrine Query Builder Error on Join: [Syntax Error] line 0, col 87: Error: Expected Literal, got 'JOIN' -