示例列表:
sample_list = [(5,16,2),(5,10,3),(5,8,1),(21,24,1)]
上面前3个元组有类似的第一个元素5,在这种情况下,只有第二个元组应该保留,因为它有最大的最后一个元素=> 3。
输出结果:
result = [(5,10,3),(21,24,1)]
1、使用defaultdict实现
参考文档:defaultdict
from collections import defaultdict sample_list = [(5,16,2),(5,10,3),(5,8,1),(21,24,1)] d = defaultdict(list) for e in sample_list: d[e[0]].append(e) res = [max(val, key=lambda x: x[2]) for val in d.values()] print(res)
2、使用itertools.groupby 和 operator.itemgetter 实现
参考文档:
from itertools import groupby
from operator import itemgetter as ig
lst = [(5, 10, 3), (21, 24, 1), (5, 8, 1), (5, 16, 2)]
[max(g, key=ig(-1)) for _, g in groupby(sorted(lst), key=ig(0))]
# [(5, 10, 3), (21, 24, 1)]
3、使用itertools.groupby实现
参考文档:itertools.groupby
rom itertools import groupby sample_list.sort() print([max(l, key=lambda x: x[-1]) for _, l in groupby(sample_list, key=lambda x: x[0])])
4、使用operator.itemgetter实现
参考文档:operator.itemgetter
from itertools import groupby from operator import itemgetter sample_list = [(5,16,2),(5,10,3),(5,8,1),(21,24,1)] sample_list.sort() print([max(l, key=itemgetter(-1)) for _, l in groupby(sample_list, key=itemgetter(0))])
或者
from operator import itemgetter sample_list = [(5,16,2),(5,10,3),(5,8,1),(21,24,1)] dct = {} for i in sample_list: if i[0] in dct: dct[i[0]].append(i) else: dct[i[0]] = [i] print([max(v, key=itemgetter(-1)) for v in dct.values()])