Home > Net >  How can a I sum a list in cycles
How can a I sum a list in cycles

Time:01-24

I need to create a list that sums values in ranges from x to x. For example, calculate the sum 2 by 2

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
listSum = sum(myList)
print(f"Sum of list -> {listSum}")

I want to achieve in the first iteration 1 2, in the next 3 4 until the last list value. I tried with a list compreension but i don't know how to do the sum.

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = [ i for i in range(myList[0],len(myList),2)]
print(list2)

I pretend obtain list2 = [3,7,11,15,19]

The problem em questions is ,for example, if my list has 240 values, I want to sum 60 in 60, sum in blocks of 60 values.

Can someone help me with this?

CodePudding user response:

Are you expecting any leftover values? Like length 15 in blocks of 4? Ill answer this with just basic python, if you want to use numpy look at AJITHs answer.

list2 = [sum(myList[i:i blockSize]) for i in range(len(myList)//blockSize  1)]

CodePudding user response:

what you need to do is first split the original list in question in parts of size 'n'. this can be done by using list comprehension to create a list of parts of the original list.

>>> original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> n = 2 # size of each chunk
>>> splits_of_og_list = [original_list[i:i n] for i in range(0, len(original_list), n)]
>>> splits_of_og_list
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]

replace n to whatever size you want and you will get chunks of size n.

then simply use the sum function over the splits_of_og_list.

>>> summed_list = [sum(split) for split in splits_of_og_list]
>>> summed_list
[3, 7, 11, 15, 19]

sum is an inbuilt function that returns the total of a iterable of integers.

CodePudding user response:

The range(start, stop, step) function can take a step which allows you to skip over values as you iterate. You then need to index the elements in myList using the iterated value.

>>> myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list2 = [myList[i-1]   myList[i] for i in range(1, len(myList), 2)]
>>> list2
[3, 7, 11, 15, 19]

Note that when there is an odd number of elements in myList, the last element is missed.

>>> myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>>> list2 = [myList[i-1]   myList[i] for i in range(1, len(myList), 2)]
>>> list2
[3, 7, 11, 15, 19]

CodePudding user response:

Using numpy

import numpy as np

myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr = np.reshape(np.array(myList), (-1, 2))
sum_arr = np.sum(arr, axis=1)
print(sum_arr)

Output:

[ 3  7 11 15 19]
  •  Tags:  
  • Related