Home >Backend Development >Python Tutorial >How Can I Efficiently Calculate the Cumulative Sum of a List of Numbers in Python?
Problem:
Given a list of numbers, we want to find the cumulative sum, which means summing up the numbers one by one from the beginning of the list. For instance, if we have a list [4, 6, 12], we want to get [4, 4 6, 4 6 12] resulting in [4, 10, 22].
Answer:
For numerical operations on arrays, it's recommended to consider NumPy, a powerful Python library. It features a convenient cumulative sum function, cumsum:
import numpy as np a = [4,6,12] np.cumsum(a) #array([4, 10, 22])
NumPy often outperforms pure Python for such tasks. Here's a comparison with another function, accumu:
In [136]: timeit list(accumu(range(1000))) 10000 loops, best of 3: 161 us per loop In [137]: timeit list(accumu(xrange(1000))) 10000 loops, best of 3: 147 us per loop In [138]: timeit np.cumsum(np.arange(1000)) 100000 loops, best of 3: 10.1 us per loop
While NumPy offers speed advantages, it's important to remember that a dependency may not be necessary if NumPy is only required for a single task.
The above is the detailed content of How Can I Efficiently Calculate the Cumulative Sum of a List of Numbers in Python?. For more information, please follow other related articles on the PHP Chinese website!