I have a list consist of tuple items like (id, cost, clicks, views)
as below:
statistic_data_list = [(12324, 9, 6, 9), (12325, 11, 5, 3), (12326, 10, 7, 2)]
And I want to get the item's id which meet following conditions:
cost
of item is equal to 0, get the item's id which cost
is lowest. cost
of item is equal 0, then if not all clicks
of item is equal to 0, get the item's id which clicks
is lowest. clicks
of item is equal to 0, then if not all views
of item is equal to 0, get the item's id which views
is lowest. # (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)
How can I get the specified item's id more efficiently?
# 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]
Any commentary is very welcome. great thanks.
You can use list comprehension for checking these. When at least one cost
among all items is not equal to zero, to get the item's id
whose cost
is lowest, try this :
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])])]
OUTPUT :
a = [12324, 12326]
Here all three items have non-zero cost
and lowest cost is 10
corresponding to which there are two ids 12324
and 12326
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.