我如何才能更有效地获取最少的商品?

时间:2019-03-13 06:40:39

标签: python filter min

我有一个列表,其中包含元组项,例如(id, cost, clicks, views),如下所示:

statistic_data_list = [(12324, 9, 6, 9), (12325, 11, 5, 3), (12326, 10, 7, 2)] 

我想获取符合以下条件的商品ID:

  • 如果并非所有项目cost都等于0,则为1,获得cost最低的项目ID。
  • 2,当所有cost项都等于0时,如果不是所有clicks都等于0,则得到clicks最低的项的ID。
  • 3当项目的所有clicks都等于0时,则如果不是所有的项目views都等于0,则获取views最低的项目ID。
# (1)
#  input:  
[(12324, 9, 6, 9), (12325, 11, 5, 3), (12326, 10, 7, 2)]
#  expected result: 
12324 # (whose cost is lowest) 

# (2)
#  input:  
[(12324, 0, 6, 9), (12325, 0, 5, 3), (12326, 0, 7, 2)]
#  expected result:
12325 #  (whose clicks is lowest when all cost is 0)

# (3)
#  input:  
[(12324, 0, 0, 9), (12325, 0, 0, 3), (12326, 0, 0, 2)]
#  expected result: 
12326  #  (whose views is lowest when all cost is 0 also clicks)

如何更有效地获取指定商品的ID?

# My attemp so far

cost_clicks_views_list = [(12324, 9, 6, 9), (12325, 11, 5, 3), (12326, 10, 7, 2)]

len_cost_not_0 = len(list(filter(lambda item: item[1], cost_clicks_views_list)))
len_clicks_not_0 = len(list(filter(lambda item: item[2], cost_clicks_views_list)))
len_views_not_0 = len(list(filter(lambda item: item[3], cost_clicks_views_list)))


if len_cost_not_0:
    min_cost_id_list = [ item[0] for item in cost_clicks_views_list if item[1]==min([i[1] for i in cost_clicks_views_list]) ]
    print(min_cost_id_list) # [(12324]

else:
    if len_clicks_not_0:
        min_clicks_id_list = [item[0] for item in cost_clicks_views_list if item[2] == min([i[2] for i in cost_clicks_views_list])]
        print(min_clicks_id_list) # [(12325]

    else:
        if len_views_not_0:
            min_views_id_list = [item[0] for item in cost_clicks_views_list if item[3] == min([i[3] for i in cost_clicks_views_list])]
            print(min_views_id_list)  # [12326]

任何评论都非常受欢迎。非常感谢。

1 个答案:

答案 0 :(得分:0)

您可以使用列表理解来检查这些内容。当所有项目中至少有一个cost不等于零时,要获取id最低的项目cost,请尝试以下方法:

sdl = [(12324, 10, 0.6, 9), (12325, 11, 0.5, 3), (12326, 10, 0.7, 2)]
a = [j[0] for j in sdl if j[1]==min([k[1] for k in sdl if all([True if i[1] != 0 else False for i in sdl])])]

输出

a = [12324, 12326]

这里所有三个项目的值都不为零,cost的最低成本为10,与此对应的是两个ID 1232412326