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