gpt4 book ai didi

python - 根据其中一个值从元组列表中删除重复项

转载 作者:太空宇宙 更新时间:2023-11-03 12:32:08 26 4
gpt4 key购买 nike

我有一个格式为 (float,string) 的元组列表。如何从列表中删除具有相同浮点值的重复项?

列表按 float 降序排列。我想保留顺序。

[(0.10507038451969995,
'Deadly stampede in Shanghai - Emergency personnel help victims.'),
(0.078586381821416265,
'Deadly stampede in Shanghai - Police and medical staff help injured people after the stampede.'),
(0.072031446647399661, '- Emergency personnel help victims.'),
(0.072031446647399661, 'Emergency personnel help victims.')]

看看最后两个。

最佳答案

您可以使用 itertools.groupby 因为您已经对这些值进行了排序。这是数据:

>>> lot
[(0.10507038451969995, 'Deadly stampede in Shanghai - Emergency personnel help victims.'),
(0.07858638182141627, 'Deadly stampede in Shanghai - Police and medical staff help injured people after the stampede.'),
(0.07203144664739966, '- Emergency personnel help victims.'),
(0.07203144664739966, 'Emergency personnel help victims.')]

演示:

>>> import itertools
>>> [next(t) for _, t in itertools.groupby(lot, lambda x: x[0])]
[(0.10507038451969995,
'Deadly stampede in Shanghai - Emergency personnel help victims.'),
(0.07858638182141627,
'Deadly stampede in Shanghai - Police and medical staff help injured people after the stampede.'),
(0.07203144664739966, '- Emergency personnel help victims.')]

这将为您提供组合在一起的第一个值。

关于python - 根据其中一个值从元组列表中删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33073563/

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