简体   繁体   English

从List,Python中获取独特的元组

[英]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') . 如果你不反转列表, ('three', 'a')将覆盖('one', 'a')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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