Delete duplicate tuples independent of order with same elements in generator Python 3.5

心已入冬 提交于 2019-12-31 07:41:28

问题


I have a generator of tuples and I need to delete tuples containing same elements. I need this output for iterating.

Input = ((1, 1), (1, 2), (1, 3), (3, 1), (3, 2), (3, 3))

Output= ((1, 1), (1, 2), (1, 3))

Order of output doesn't matter.

I have checked this question but it is about lists: Delete duplicate tuples with same elements in nested list Python

I use generators to achieve fastest results as the data is very large.


回答1:


You can normalize the data by sorting it, then add it to a set to remove duplicates

>>> Input = ((1, 1), (1, 2), (1, 3), (3, 1), (3, 2), (3, 3))
>>> Output = set(tuple(sorted(t)) for t in Input)
>>> Output
{(1, 2), (1, 3), (2, 3), (1, 1), (3, 3)}


来源:https://stackoverflow.com/questions/40850892/delete-duplicate-tuples-independent-of-order-with-same-elements-in-generator-pyt

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