使用groupby过滤器后应用jinja过滤器 [英] Applying a jinja filter after using groupby filter

查看:162
本文介绍了使用groupby过滤器后应用jinja过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典列表,我想按某个属性进行分组,然后相加。对于一个变量'foo',这可能是这样的:

  foo | groupby('a')| sum(attribute ='b')

这显然不起作用,因为在 groupby ,我有一个元组列表。有没有办法解开元组然后重新打包它,这样我就可以维护 groupby 完成的工作,但是可以处理第二个元组的值?

解决方案

您可以使用 map()过滤器可将总和应用于每个组,只要您先提取组列表:

foo | groupby('a')| map(attribute ='list')| map('sum',attribute ='b')

这是因为 map ()将第一个参数作为另一个过滤器,其余参数传递给该过滤器,将该过滤器应用于 groupby()



这意味着你最终会得到一个总和列表,而不是组。无法对组进行总和并保留 .grouper 属性。为此,唯一的解决方案是使用一个实际的循环:

  {%for group in foo | groupby('a')%} 
{{group.grouper}}:{{group.list | sum(attribute ='b')}}
{%endfor%}

会输出每个不同的值 a 后跟一个冒号,并且该组的属性 b 的总和。


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 | 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?

解决方案

You can use the map() filter to apply a sum to each group, provided you extract the group list first:

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().

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:

{% 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.

这篇关于使用groupby过滤器后应用jinja过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆