【问题标题】:Filtering a list of tuples by the first value and checking presence of a second item in the tuple using list comp [duplicate]按第一个值过滤元组列表并使用 list comp 检查元组中是否存在第二个项目 [重复]
【发布时间】: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


【解决方案1】:

你也可以使用set,例如

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')]
a.sort(key=lambda x: x[0],reverse=True)#sort by 1 tuple value
ans = []
s = set() #we save the values of names that have already been used
for i in a:
    if i[1] not in s:
        ans.append(i)
        s.add(i[1])
del s
print(ans)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-04
    • 1970-01-01
    • 2023-03-03
    • 2016-03-17
    • 2010-10-23
    相关资源
    最近更新 更多