本文介绍了如果每个元组中的第二个项目是重复的,我如何从元组列表中删除元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果每个元组中的第二个项目是重复的,我如何从元组列表中删除元素?
How do I remove element from a list of tuple if the 2nd item in each tuple is a duplicate?
例如,我有一个按第1个元素排序的列表看起来像这样:
For example, I have a list sorted by 1st element that looks like this:
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'),]
所需的输出离开元组最高的第一个项目应该是:
The desired output leave the tuple with the highest 1st item, should be:
alist = [(0.7897897,'this is a foo bar sentence'),
(0.325345, 'this is not really a foo bar')]
推荐答案
如果您的 alist
已经按第一个元素从最高到最低排序:
If your alist
is already sorted by the first element from highest to lowest:
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
is now:
[(0.7897897, 'this is a foo bar sentence'),
(0.325345, 'this is not really a foo bar')]
这篇关于如果每个元组中的第二个项目是重复的,我如何从元组列表中删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!