简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM