appleLover appleLover - 1 year ago 92
Python Question

Get Unique Tuples from List , Python

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

Answer Source

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
[('one', 'a'), ('two', 'b')]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download