-1

I have 2 list A and B, list A contain values I want list B to be the sum of value from list a

A = [3,5,7,8,9,12,13,20]
#Wanted result
#B = [3, 8, 15, 23,...77]
#so the new value will be the sum of the old value
# [x1, x2+x1, x3+x2+x1,... xn+xn+xn]

what methods I could use to get the answer, thank you.

  • 1
    Does this answer your question? [How to find the cumulative sum of numbers in a list?](https://stackoverflow.com/questions/15889131/how-to-find-the-cumulative-sum-of-numbers-in-a-list) – kaya3 Sep 04 '21 at 23:58

1 Answers1

1

The easiest way IMO would be to use numpy.cumsum, to get the cumulative sum of your list:

>>> import numpy as np
>>> np.cumsum(A)
array([ 3,  8, 15, 23, 32, 44, 57, 77])

But you also could do it in a list comprehension like this:

>>> [sum(A[0:x]) for x in range(1, len(A)+1)]
[3, 8, 15, 23, 32, 44, 57, 77]

Another fun way is to use itertools.accumulate, which gives accumulated sums by default:

>>> from itertools import accumulate
>>> list(accumulate(A))
[3, 8, 15, 23, 32, 44, 57, 77]
sacuL
  • 49,704
  • 8
  • 81
  • 106
  • `itertools.accumulate` or `functools.reduce` is the way to go. For someone who doesn’t know how to add consecutive numbers in a list, `numpy` is overkill. – Abhijit Sarkar Sep 05 '21 at 00:25