Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Unique Tuples from List , Python

Tags:

python

list

set

>>> a= ('one', 'a')
>>> b = ('two', 'b')
>>> c = ('three', 'a')
>>> l = [a, b, c]
>>> l
[('one', 'a'), ('two', 'b'), ('three', 'a')]

How can I check for only the elements of this list with a unique second entry (column? item?), and then grab the first entry found on the list. Desired output is

>>> l
[('one', 'a'), ('two', 'b')]
like image 238
appleLover Avatar asked Sep 05 '13 19:09

appleLover


2 Answers

Use a set (if the second item is hash-able):

>>> lis = [('one', 'a'), ('two', 'b'), ('three', 'a')]
>>> seen = set()
>>> [item for item in lis if item[1] not in seen and not seen.add(item[1])]
[('one', 'a'), ('two', 'b')]

The above code is equivalent to:

>>> seen = set()
>>> ans = []
for item in lis:
    if item[1] not in seen:
        ans.append(item)
        seen.add(item[1])
...         
>>> ans
[('one', 'a'), ('two', 'b')]
like image 67
Ashwini Chaudhary Avatar answered Sep 22 '22 20:09

Ashwini Chaudhary


If order isn't important, you can use a dictionary:

d = {}

for t in reversed(l):
    d[t[1]] = t

print d.values()

Or more concisely:

{t[1]: t for t in reversed(l)}.values()

If you don't reverse the list, ('three', 'a') will overwrite ('one', 'a').

like image 30
Blender Avatar answered Sep 25 '22 20:09

Blender