gpt4 book ai didi

python - 如果每个元组中的第二项重复,如何从元组列表中删除元素?

转载 作者:太空宇宙 更新时间:2023-11-03 13:02:28 24 4
gpt4 key购买 nike

如果每个元组中的第二项重复,我如何从元组列表中删除元素?

例如,我有一个按第一个元素排序的列表,如下所示:

alist = [(0.7897897,'this is a foo bar sentence'),
(0.653234, 'this is a foo bar sentence'),
(0.353234, 'this is a foo bar sentence'),
(0.325345, 'this is not really a foo bar'),
(0.323234, 'this is a foo bar sentence'),]

期望的输出离开具有最高第一项的元组,应该是:

alist = [(0.7897897,'this is a foo bar sentence'),
(0.325345, 'this is not really a foo bar')]

最佳答案

如果您的 alist 已经按第一个元素从高到低排序:

alist = [(0.7897897,'this is a foo bar sentence'),
(0.653234, 'this is a foo bar sentence'),
(0.353234, 'this is a foo bar sentence'),
(0.325345, 'this is not really a foo bar'),
(0.323234, 'this is a foo bar sentence'),]

seen = set()
out = []
for a,b in alist:
if b not in seen:
out.append((a,b))
seen.add(b)

out 现在是:

[(0.7897897, 'this is a foo bar sentence'),
(0.325345, 'this is not really a foo bar')]

关于python - 如果每个元组中的第二项重复,如何从元组列表中删除元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15090039/

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