Applying a jinja filter after using groupby filter

陌路散爱 提交于 2019-12-12 15:23:01

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/28006299/applying-a-jinja-filter-after-using-groupby-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!