3

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

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

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

1 回答 1

8

如果您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')]
于 2013-02-26T13:16:17.677 回答