gpt4 book ai didi

python - 从列表中获取唯一元组,Python

转载 作者:太空狗 更新时间:2023-10-29 18:00:19 26 4
gpt4 key购买 nike

>>> a= ('one', 'a')
>>> b = ('two', 'b')
>>> c = ('three', 'a')
>>> l = [a, b, c]
>>> l
[('one', 'a'), ('two', 'b'), ('three', 'a')]

我如何才能只检查此列表中具有唯一第二个条目(列?项目?)的元素,然后获取在列表中找到的第一个条目。期望的输出是

>>> l
[('one', 'a'), ('two', 'b')]

最佳答案

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

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

上面的代码等价于:

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

关于python - 从列表中获取唯一元组,Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18644091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com