Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(PYTHON) How to ALTOGETHER Add every Nth term of elements inside list to produce new list?

Let's say we have following list

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]

Now I want to add every 3 numbers together to provide length of 6 list thus,

[6, 15, 24, 33, 42, 51]

I want to do this in python.... please help! (was my question worded weirdly,,?)

Until now I tried

z = np.zeros(6)
p = 0
cc = 0
for i in range(len(that_list)):
    p += that_list[i]
    cc += 1
    if cc == 3:
       t = int((i+1)/3)
       z[t] = p
       cc = 0
       p = 0

and it did not work....

like image 793
Daniel Kwon Avatar asked Nov 18 '25 15:11

Daniel Kwon


2 Answers

Consider using a list comprehension:

>>> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
>>> [sum(nums[i:i+3]) for i in range(0, len(nums), 3)] 
[6, 15, 24, 33, 42, 51]

Or numpy:

>>> import numpy as np
>>> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
>>> np.add.reduceat(nums, np.arange(0, len(nums), 3))
>>> array([ 6, 15, 24, 33, 42, 51])

If you need to use a manual loop for some reason:

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
result = []
group_size, group_sum, group_length = 3, 0, 0
for num in nums:
    group_sum += num
    group_length += 1
    if group_length == group_size:
        result.append(group_sum)
        group_sum, group_length = 0, 0
print(result)  # [6, 15, 24, 33, 42, 51]
like image 111
Sash Sinha Avatar answered Nov 21 '25 06:11

Sash Sinha


You can create an iterator from the list, zip the iterator for 3 times and map the sequence to sum for output:

>>> i = iter([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18])
>>> list(map(sum, zip(i, i, i)))
[6, 15, 24, 33, 42, 51]
like image 22
blhsing Avatar answered Nov 21 '25 04:11

blhsing



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!