Home > OS >  How to get total sum in multiple lists using python
How to get total sum in multiple lists using python

Time:04-08

[templatetag.py]

def total_sum(value):
    value_list = value[:, 1:]
    return [sum(i) for i in zip(*value_list)]

[html]

{% load total_sum from templatetag %}

<tr>
  <td>Monthly Total</td>
  <td>{{ monthly_enroll_list|total_sum }}</td> <!-- Total (Jan) -->
  <td>{{ monthly_enroll_list }}</td> <!-- Total (Feb) -->
  <td>{{ monthly_enroll_list }}</td> <!-- Total (Mar) -->
  <td>{{ monthly_enroll_list }}</td>
  <td>{{ monthly_enroll_list }}</td>
  <td>{{ monthly_enroll_list }}</td>
  <td>{{ monthly_enroll_list }}</td>
  <td>{{ monthly_enroll_list }}</td>
  <td>{{ monthly_enroll_list }}</td>
  <td>{{ monthly_enroll_list }}</td>
  <td>{{ monthly_enroll_list }}</td>
  <td>{{ monthly_enroll_list }}</td>
</tr>
  1. The value of the "monthy_enroll_list" variable is as follows.

[['A', 3, 1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8], ['B', 1, 8, 6, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1], ['C', 0, 1, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 2], ['D', 2, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]]

  1. If I remove the index at the beginning and the end of each list, I get the number of enrolls from January to December. I want to get the total sum per month. The values ​​I want to get are:

['6', '10', '12', '6', '0', '0', '0', '0', '0', '0', '0', '0']

  1. But i got the following error:

list indices must be integers or slices, not tuple

Thanks for letting me know how to solve it

CodePudding user response:

The issue is the zip function that you're calling. Taking your function, let's focus on the zip part:

# your current function
def total_sum(value):
    value_list = value[:, 1:]
    return [sum(i) for i in zip(*value_list)]

Let's suppose our value is:

v = [[1,2,3], [4,5,6], [7,8,9]]

If we do:

print(list(zip(*v))

We get:

>>> [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

This isn't something we can call sum on as you would be trying to sum a list of tuples.

So instead of

return [sum(i) for i in zip(*value_list)]

in the last line of function, you could change that to:

total = 0
for inner_list in values_list:
    total  = sum(inner_list)
return total

Your new function would therefore become:

def total_sum(value):
    value_list = value[:, 1:]
    total = 0
    for inner_list in values_list:
        total  = sum(inner_list)
    return total
  • Related