不同深度字典的列表理解

List comprehension with different depth dictionaries

我有两本结构如下的词典:

  1. Quantity[week][day][time]
  2. Cost[day][time]

目标是将列表理解乘以数量 * 成本,然后求和。 Cost 所有周都相同,但是数量会因周而异。在将星期添加到第一本词典之前,我有以下内容:

sum([Cost[day][time]*Quantity[day][time] for day,time in zip(df,tf)])

它按预期工作。
既然 Quantity 字典多了一层,有没有办法通过列表理解实现同样的效果?

编辑

我希望每周都有不同的结果。应该是
sum(week1)+sum(week2)+...+sum(weekn)

像这样添加一个周变量:

[sum(cost[day][time]*q[week][day][time] for day,time in zip(df,tf)) for week in wf]

这是一个输出示例:

q = {'week1': {'day1': {'time1': 21, 
                        'time2': 30}, 
               'day2': {'time1': 21, 
                        'time2': 40}}, 
     'week2': {'day1': {'time1': 22, 
                        'time2': 9}, 
               'day2': {'time1': 23, 
                        'time2': 24}}}

cost = {'day1': {'time1': 21, 
                'time2': 24}, 
        'day2': {'time1': 22, 
                 'time2': 23}}

wf = ['week1', 'week2']
df = ['day1', 'day2']
tf = ['time1', 'time2']

output = [sum(cost[day][time]*q[week][day][time] for day,time in zip(df,tf)) for week in wf]

print(output)

输出:

[1361, 1014]

输出是每周总和的列表,因此 'week1' 总和为 1361,'week2' 总和为 1014。