I have a list of dictionaries that I want to group by a certain attribute and then sum by another. For a variable 'foo' this would be something like:
我有一个字典列表,我想按某个属性分组,然后用另一个属性求和。对于变量'foo',这将是这样的:
foo | groupby('a') | sum(attribute='b')
This clearly won't work because after the groupby
, I have a list of tuples. Is there any way to unpack the tuple and then repack it, so that i can maintain the work done by groupby
, but work on the second tuple value?
这显然是行不通的,因为在groupby之后,我有一个元组列表。有没有办法解开元组然后重新打包它,这样我就可以维护groupby完成的工作,但是可以处理第二个元组值吗?
1 个解决方案
#1
2
You can use the map()
filter to apply a sum to each group, provided you extract the group list first:
如果先提取组列表,则可以使用map()过滤器将总和应用于每个组:
foo | groupby('a') | map(attribute='list') | map('sum', attribute='b')
That's because map()
takes the first argument as another filter, and the remainder of the arguments are passed to that filter, applying that filter to each element of groupby()
.
这是因为map()将第一个参数作为另一个过滤器,并将其余参数传递给该过滤器,将该过滤器应用于groupby()的每个元素。
This does mean you end up with a list of sums, not with groups.
这意味着您最终会得到一个总和列表,而不是组。
You cannot apply the summing to the groups and leave the .grouper
attribute in place. For that the only solution is to use an actual loop:
您无法将汇总应用于组并保留.grouper属性。为此,唯一的解决方案是使用实际循环:
{% for group in foo | groupby('a') %}
{{ group.grouper }}: {{ group.list | sum(attribute='b') }}
{% endfor %}
would output each distinct value of a
followed by a colon and the sum of attribute b
for that group.
将输出a的每个不同值,后跟冒号和该组的属性b的总和。
#1
2
You can use the map()
filter to apply a sum to each group, provided you extract the group list first:
如果先提取组列表,则可以使用map()过滤器将总和应用于每个组:
foo | groupby('a') | map(attribute='list') | map('sum', attribute='b')
That's because map()
takes the first argument as another filter, and the remainder of the arguments are passed to that filter, applying that filter to each element of groupby()
.
这是因为map()将第一个参数作为另一个过滤器,并将其余参数传递给该过滤器,将该过滤器应用于groupby()的每个元素。
This does mean you end up with a list of sums, not with groups.
这意味着您最终会得到一个总和列表,而不是组。
You cannot apply the summing to the groups and leave the .grouper
attribute in place. For that the only solution is to use an actual loop:
您无法将汇总应用于组并保留.grouper属性。为此,唯一的解决方案是使用实际循环:
{% for group in foo | groupby('a') %}
{{ group.grouper }}: {{ group.list | sum(attribute='b') }}
{% endfor %}
would output each distinct value of a
followed by a colon and the sum of attribute b
for that group.
将输出a的每个不同值,后跟冒号和该组的属性b的总和。