【发布时间】:2020-10-13 12:40:16
【问题描述】:
我有一个这样的列表:
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')]
我想获得以下信息(列表推导是我想要实现的):
[(1800000.0, 'google'), (1440000.0, 'IBM'), (720000.0, 'FB')]
基本上,获取每个元组的每个唯一第二个参数的最大值。
我尝试过的(伪):
[max(x) for x in a if x[1] not in this list]
# I don't know if / how I can refer to the list comprehension list while
# its being built
【问题讨论】:
-
一般来说,你不能在构建列表理解时引用它
-
@RajatMishram 不确定在我的情况下我将如何使用
[max(items) for key, items in groupby(L,key = itemgetter(1))],L代表什么?这也提供了输出中提到的每个元组。不是唯一的。 -
"L" 是列表的名称,因此在您的示例中为“a”。
-
@Rivers 使用
[max(items) for key, items in groupby(a,key = itemgetter(1))]给了我完整的列表,而不是只有 3 项唯一的元组中的第二项。
标签: python list filter list-comprehension