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....
CodePudding user response:
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]
CodePudding user response:
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]