简体   繁体   中英

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

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

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