Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Summing x elements in a list

Tags:

python

list

sum

i wasn't able to find the answer using the search function so i am starting this thread.

Consider having a list that is divideable by x. For example:

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

The example x would be 3 in this case.

Now i want to create a new list with

len(onetonine)/x

elements, which would mean 3 elements.

The important part is, that i want the elements of the new list to be the sum of every x elements of the old list. This means:

newlist = [6, 15, 24]

So basically take x=3 elements of my old list and add them. Repeat until done.

I wasn't able to get a working solution for this so i am asking for help.

Thank you.

like image 933
TolleWurst Avatar asked May 24 '26 21:05

TolleWurst


2 Answers

The following list comprehension of the sums of the appropriate slices will work:

>>> [sum(onetonine[i:i+3]) for i in range(0, len(onetonine), 3)]
[6, 15, 24]

Note: this will not discard any rest if the length of the original list is not divisible by the chunk length but just add the sum of the last (shorter) chunk.

like image 121
user2390182 Avatar answered May 26 '26 10:05

user2390182


Using zip(*([iter(onetonine)]*3)) which splits the list into 3 sub-lists

onetonine = [1,2,3,4,5,6,7,8,9]
[sum(i) for i in zip(*([iter(onetonine)]*3))]
#[6, 15, 24]
like image 27
Transhuman Avatar answered May 26 '26 10:05

Transhuman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!