列表理解,如果不在第二列表中,则为值

时间:2018-09-28 13:42:36

标签: python

如果某周存在于sales中,否则是否可以使用列表推导来获得每周的销售额?

weeks = [{'week': 31}, {'week': 32}, {'week': 33}, 
         {'week': 34}, {'week': 35}, {'week': 36}]
weeks = [x['week'] for x in weeks]

sales = [
    {'week': 32, 'sales': 1167.26}, 
    {'week': 33, 'sales': 1373.61}, 
    {'week': 36, 'sales': 1491.43}, 
]

expected = [0, 1167.26, 1373.61, 0, 0, 1491.43]

4 个答案:

答案 0 :(得分:3)

您可以从sales创建一个字典,以用作weeks中每周的查询:

weeks = [{'week': 31}, {'week': 32}, {'week': 33}, 
     {'week': 34}, {'week': 35}, {'week': 36}]

sales = [
{'week': 32, 'sales': 1167.26}, 
{'week': 33, 'sales': 1373.61}, 
{'week': 36, 'sales': 1491.43}, 
]
_sales = {i['week']:i['sales'] for i in sales}
results = [_sales.get(i['week'], 0) for i in weeks]

输出:

[0, 1167.26, 1373.61, 0, 0, 1491.43]

答案 1 :(得分:0)

如果您保证给定的sales值中只有week的一个元素,则可以获取一系列的销售价值,将这些总和求和以获得任意给定的一周的价值:

out = [
    sum(sale['sales'] for sale in sales if sale['week'] == week)
    for week in weeks
]

如果对于任何给定的sales,在week中有多个条目,则将其结果相加,以产生销售输出的总价值。

这为您提供了具有所需输出的单个列表理解:

输出:

[0, 1167.26, 1373.61, 0, 0, 1491.43]

答案 2 :(得分:0)

说,创建周数到销售额的中间映射,例如

week_sales = {s['week']: s['sales'] for s in sales}

expected = [week_sales.get(w['week'], 0) for w in weeks]

答案 3 :(得分:0)

如果可以使用熊猫等第三方库

import pandas as pd
weeks = [{'week': 31}, {'week': 32}, {'week': 33}, 
         {'week': 34}, {'week': 35}, {'week': 36}]
df1=pd.DataFrame(weeks)    

sales = [
    {'week': 32, 'sales': 1167.26}, 
    {'week': 33, 'sales': 1373.61}, 
    {'week': 36, 'sales': 1491.43}, 
]
df2=pd.DataFrame(sales)

df1.merge(df2,how='left').fillna(0)

输出

week    sales
31      0.00
32      1167.26
33      1373.61
34      0.00
35      0.00
36      1491.43

如果您在同一周的销售清单中有多个条目

import pandas as pd
weeks = [{'week': 31}, {'week': 32}, {'week': 33}, 
         {'week': 34}, {'week': 35}, {'week': 36}]
df1=pd.DataFrame(weeks) 

sales = [
    {'week': 32, 'sales': 1167.26}, 
    {'week': 33, 'sales': 1373.61}, 
    {'week': 36, 'sales': 1491.43}, 
    {'week': 36, 'sales': 5}, 
]
df2=pd.DataFrame(sales)

pd.DataFrame(df1.merge(df2,how='left').fillna(0).groupby('week')['sales'].sum(name='sales'))

week    sales
31      0.00
32      1167.26
33      1373.61
34      0.00
35      0.00
36      1496.43

受@ Ajax1234解决方案的启发,如果您一周内有多个销售价值,则可以创建包含分组价值的字典

weeks = [{'week': 31}, {'week': 32}, {'week': 33}, 
         {'week': 34}, {'week': 35}, {'week': 36}]
sales = [
    {'week': 32, 'sales': 1167.26}, 
    {'week': 33, 'sales': 1373.61}, 
    {'week': 36, 'sales': 1491.43}, 
    {'week': 36, 'sales': 5}, 
]

sales_dict={}
for i in sales:
    if i['week'] in sales_dict:
        sales_dict[i['week']]=sales_dict[i['week']]+i['sales']
    else:
        sales_dict[i['week']]=i['sales']
[sales_dict.get(i['week'],0) for i in weeks] # sales_dict= {32: 1167.26, 33: 1373.61, 36: 1496.43}

输出

[0, 1167.26, 1373.61, 0, 0, 1496.43]