Jinja template to access nested lists and do aggregations on results

Allo

I want to access values in certain index positions nested in an attribute and do some arithmetic with the results.

Can anyone help?

This should render in template dev tool ok.

#I got data like this in an attribute:
{% set  giraffesMatches = [[874,943,22,22],[955,938,30,30],[955,934,20,20]] %}
{{giraffesMatches}}


I want to sum the product of the 3rd and 4th values.  
(22*22) + (30*30) + (20*20) = 1784
{{(22*22) + (30*30) + (20*20)}}

Actually they are always the same values so this would be ok too
(22**2) + (30**2) + (20**2) = 1784
{{(22*22) + (30*30) + (20*20)}}

I can access and sum the 3rd values like this:
{{giraffesMatches|sum(attribute='3')}}

Or return them in a loop like this:

{% for index in giraffesMatches -%}
  {%- if not loop.last %}
    {{- index[3] -}},
  {%- else -%}
    {{index[3]}}
  {% endif -%}
{%- endfor %}

But I can't actually figure out how to sum the squares or products.
{% for index in giraffesMatches -%}
  {%- if not loop.last %}
    {{- index[3]**2 -}}+
  {%- else -%}
    {{index[3]**2}}
  {% endif -%}
{%- endfor %}

It would also be handy for something related if I could do a max rather than a sum like this 
giraffesMatches|sum(attribute='3')
giraffesMatches|max(attribute='3')
{% set giraffesMatches = [[874,943,22,22],[955,938,30,30],[955,934,20,20]] %}
{% set out = namespace(value=0) %}
{% for index in giraffesMatches %}
  {% set out.value = out.value + (index[2] * index[3]) %}
{% endfor %}

{{ out.value }}

image

1 Like

Legend. Ta!

Chris that worked a treat. Would you be so kind as to help me with the next bit too? I want the max of the 3rd values.

{% set giraffesMatches = [[874,943,22,22],[955,938,30,30],[955,934,20,20]] %}

This sums the 3rd values
{{giraffesMatches|sum(attribute='3')}}
i.e 22+30+20 = 72)

But I want the max of the 3rd value. i.e max(22,30,20) = 30
say like:  giraffesMatches|max(attribute='3') ~  but you can't do a max like this! 

This works for the above^^^^^. Not sure if there’s a more concise way to do it?

{% set giraffesMatches = [[874,943,20,22],[955,938,30,30],[955,934,50,20],[955,934,99,99]] %}

{{ giraffesMatches }}

{% set out = namespace(value=0) %}
{% for index in giraffesMatches %}
  {% if out.value > (index[2]) %}
     {% set out.value = out.value  %}
  {% else %}
     {% set out.value = index[2]  %}
  {% endif %}
{% endfor %}
{{ out.value }}


(max of 3rd value = 99)