>>> 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')]
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')]
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')
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With