【发布时间】:2020-10-13 13:44:56
【问题描述】:
我有一个这样的列表:
a = [(1800000.0, 'google'), (1440000.0, 'IBM'), (1260000.0, 'google'), (1008000.0, 'IBM'),
(990000.0, 'google'), (792000.0, 'IBM'), (720000.0, 'FB'), (600000.0, 'google'),
(504000.0,'FB'), (480000.0, 'IBM'), (420000.0, 'google'), (400000.0, 'google'),
(396000.0, 'FB'), (336000.0, 'IBM'), (330000.0, 'google'), (320000.0, 'IBM'),
(280000.0, 'google'), (264000.0, 'IBM'), (240000.0, 'FB'), (224000.0, 'IBM'),
(220000.0, 'google'), (176000.0, 'IBM'), (168000.0, 'FB'), (160000.0, 'FB'),
(132000.0, 'FB'), (112000.0, 'FB'), (88000.0, 'FB')]
我想使用 itemgetter 获得以下信息。它是每个元组第二项唯一的元组中第一项的最大值:
[(1800000.0, 'google'), (1440000.0, 'IBM'), (720000.0, 'FB')]
我尝试过的:
[max(items) for key, items in groupby(a,key = itemgetter(1))]
但它返回完整列表,虽然它是accepted answer。
如何使用 itemgetter 和列表理解实现所需的输出?
【问题讨论】:
-
您需要按元组中的第二项对
a进行排序,才能正确使用groupby
标签: python list list-comprehension