Getting unique tuples from a list [duplicate]

こ雲淡風輕ζ 提交于 2020-02-24 00:39:40

问题


I have a list of tuples whose elements are like this:

aa = [('a', 'b'), ('c', 'd'), ('b', 'a')] 

I want to treat ('a', 'b') and ('b', 'a') as the same group and want to extract only unique tuples. So the output should be like this:

[('a', 'b'), ('c', 'd')]

How can I achieve this efficiently as my list consists of millions of such tuples?


回答1:


Convert to a frozenset, hash, and retrieve:

In [193]: map(tuple, set(map(frozenset, aa))) # python2
Out[193]: [('d', 'c'), ('a', 'b')]

Here's a slightly more readable version with a list comprehension:

In [194]: [tuple(x) for x in set(map(frozenset, aa))]
Out[194]: [('d', 'c'), ('a', 'b')]

Do note that, for your particular use case, a list of tuples isn't the best choice of data structure. Consider storing your data as a set to begin with?

In [477]: set(map(frozenset, aa))
Out[477]: {frozenset({'a', 'b'}), frozenset({'c', 'd'})}



回答2:


Given order doesn't matter just convert to set and frozenset, this seems like a better data structure fit than list and tuple, e.g.:

>>> {frozenset(x) for x in aa}
{frozenset({'c', 'd'}), frozenset({'a', 'b'})}


来源:https://stackoverflow.com/questions/45756050/getting-unique-tuples-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!