Home > Software engineering >  How to find the sum of every 4 elements of a list
How to find the sum of every 4 elements of a list

Time:10-08

Like here is a list:

[2,2,2,2,3,3,3,3,4,4,4,4]

Here is the output I want:

output:

[8,12,16]

CodePudding user response:

You can do like this,

In [1]: l = [2,2,2,2,3,3,3,3,4,4,4,4]

In [2]: [sum(l[i:i 4]) for i in range(0, len(l), 4)]
Out[2]: [8, 12, 16]

CodePudding user response:

You can use this:

from math import ceil
result = []
for i in range(ceil(len(L)/4)):
    result  = [sum(L[i*4:i*4 4])]

If you want to avoid importing ceil, here's another way:

result = []
for i in range((len(L) 3)//4):
    result  = [sum(L[i*4:i*4 4])]

These solutions work even when the list length is not a multiple of 4, in which case the remaining elements are summed together. So the output for a list like

L = [2,2,2,2,3,3,3,3,4,4,4,4,5,3]

Would be:

[8, 12, 16, 8]

CodePudding user response:

Another option by grouping your list to a list of lists with each 4 values using the grouper function and then sum the values in each list like this:

from more_itertools import grouper
your_list = [2,2,2,2,3,3,3,3,4,4,4,4]
your_lists = list(grouper(4, your_list))
list(map(sum, your_lists))

Output:

[8, 12, 16]
  • Related