How do I remove element from a list of tuple if the 2nd item in each tuple is a duplicate?

萝らか妹 提交于 2020-01-14 19:18:07

问题


How do I remove element from a list of tuple if the 2nd item in each tuple is a duplicate?

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

回答1:


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


来源:https://stackoverflow.com/questions/15090039/how-do-i-remove-element-from-a-list-of-tuple-if-the-2nd-item-in-each-tuple-is-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!