简体   繁体   English

Django,如何对字典值中的查询集值求和

[英]Django, how to sum queryset value in dictionary values

I have the following queryset dictionary:我有以下查询集字典:

{'Key_1': [100.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
 'Key_2': [103.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}

In which I have as Key the category of my products and as items 12 values, that represent the sum of each month.其中我将我的产品类别作为键,并将项目 12 值作为每个月的总和。 I want to calculate the cross sum of all keys of each items, as the following example:我想计算每个项目的所有键的交叉和,如下例所示:

{'Total': [203.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}

How could I obtain it?我怎么能得到它?

You can use zip , sum , and list comprehension:您可以使用zipsum和列表理解:

d = {
    'Key_1': [100.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 
    'Key_2': [103.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
}

sum_dict = {
    'Total': [sum(t) for t in zip(*d.values())],
}
# sum_dict = {'Total': [203.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}

Step-by-step explanation of [sum(t) for t in zip(*d.values())] : [sum(t) for t in zip(*d.values())]的逐步说明:

  1. [sum(t) for t in zip([100.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [103.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])]
  2. [sum(t) for t in [(100.0, 103.0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]]
  3. [sum((100.0, 103.0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0)), sum((0, 0))]
  4. [203.0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM