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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With