如果返回的顺序无关紧要,可以尝试使用groupby
fromitertools
将项目按第一个元素分组(按第一个元素排序后),然后用函数拉出最大值max
(另外,需要注意的是,这个返回一个新列表,而不是就地修改):
In [1]: from itertools import groupby
In [2]: l = [[['a'],[24],214,1] ,[['b'],[24],312,1] ,[['a'],[24],3124,1] , [['c'],[24],34,1]]
In [3]: result = []
In [4]: for k, g in groupby(sorted(l, key=lambda x: x[0]), key=lambda x: x[0]):
...: result.append(max(g, key=lambda m: m[2]))
...:
...:
In [5]: result
Out[5]: [[['a'], [24], 3124, 1], [['b'], [24], 312, 1], [['c'], [24], 34, 1]]
稍微扩展一下,如果要保持原始顺序,可以l
通过仅包含 are in 的那些项目进行修改results
,这将保持顺序:
In [6]: l = [i for i in l if i in result]
In [7]: l
Out[7]: [[['b'], [24], 312, 1], [['a'], [24], 3124, 1], [['c'], [24], 34, 1]]
并将其组合成一个真正可憎的单线,你可以(但可能不应该:))这样做:
In [10]: l = [[['a'],[24],214,1] ,[['b'],[24],312,1] ,[['a'],[24],3124,1] , [['c'],[24],34,1]]
In [11]: [i for i in l if i in [max(g, key=lambda m: m[2]) for k, g in groupby(sorted(l, key=lambda x: x[0]), key=lambda x: x[0])]]
Out[11]: [[['b'], [24], 312, 1], [['a'], [24], 3124, 1], [['c'], [24], 34, 1]]