[英]Problem in getting unique elements from list of tuples
I got sample input as a=[(1,2),(2,3),(1,1),(2,1)]
, and the expected ouput is a=[(1,2),(2,3),(1,1)]
. 我得到的样本输入为
a=[(1,2),(2,3),(1,1),(2,1)]
,并且预期的输出为a=[(1,2),(2,3),(1,1)]
。
Here, (2,1) is removed, since the same combinational pair (1,2) is already available. 这里,(2,1)被删除,因为相同的组合对(1,2)已经可用。 I tried below code to remove duplicate pairs
我尝试下面的代码删除重复的对
map(tuple, set(frozenset(x) for x in a))
However, the output is [(1, 2), (2, 3), (1,)]
. 但是,输出为
[(1, 2), (2, 3), (1,)]
。 How to get (1,1) pair as (1,1) instead of (1,). 如何将(1,1)对作为(1,1)而不是(1,)。
You can use a dict instead of a set to map the frozensets to the original tuple values. 您可以使用字典而不是集合来将冻结集映射到原始元组值。 Build the dict in reversed order of the list so that duplicating tuples closer to the front can take precedence:
以列表的相反顺序构建dict,以便复制更靠近最前面的元组可以优先:
{frozenset(x): x for x in reversed(a)}.values()
This returns: 返回:
[(1, 2), (2, 3), (1, 1)]
This is one approach using sorted
这是使用
sorted
一种方法
Ex: 例如:
a=[(1,2),(2,3),(1,1),(2,1)]
print set([tuple(sorted(i)) for i in a])
Output: 输出:
set([(1, 2), (2, 3), (1, 1)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.