Darknight
Darknight

Reputation: 1152

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)].

Here, (2,1) is removed, since the same combinational pair (1,2) is already available. 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,)]. How to get (1,1) pair as (1,1) instead of (1,).

Upvotes: 1

Views: 67

Answers (2)

blhsing
blhsing

Reputation: 106435

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:

{frozenset(x): x for x in reversed(a)}.values()

This returns:

[(1, 2), (2, 3), (1, 1)]

Upvotes: 3

Rakesh
Rakesh

Reputation: 82755

This is one approach using 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)])

Upvotes: 1

Related Questions