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

app*_*ver 11 python list set

>>> a= ('one', 'a')
>>> b = ('two', 'b')
>>> c = ('three', 'a')
>>> l = [a, b, c]
>>> l
[('one', 'a'), ('two', 'b'), ('three', 'a')]
Run Code Online (Sandbox Code Playgroud)

如何仅使用唯一的第二个条目(列?项?)检查此列表的元素,然后获取列表中的第一个条目.期望的输出是

>>> l
[('one', 'a'), ('two', 'b')]
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 15

使用一个集合(如果第二个项目是可散列的):

>>> 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')]
Run Code Online (Sandbox Code Playgroud)

上面的代码相当于:

>>> 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')]
Run Code Online (Sandbox Code Playgroud)

  • 我终于理解了这个列表的理解."seen.add()"代码总是返回None,所以说"而不是......总是无"根本不是检查的条件,只是一种将命令隐藏到列表理解中的方法. (2认同)