How to find the cumulative sum of numbers in a list?

前端 未结 21 1908
挽巷
挽巷 2020-11-22 02:09
time_interval = [4, 6, 12]

I want to sum up the numbers like [4, 4+6, 4+6+12] in order to get the list t = [4, 10, 22].

21条回答
  •  执念已碎
    2020-11-22 02:48

    In Python 2 you can define your own generator function like this:

    def accumu(lis):
        total = 0
        for x in lis:
            total += x
            yield total
    
    In [4]: list(accumu([4,6,12]))
    Out[4]: [4, 10, 22]
    

    And in Python 3.2+ you can use itertools.accumulate():

    In [1]: lis = [4,6,12]
    
    In [2]: from itertools import accumulate
    
    In [3]: list(accumulate(lis))
    Out[3]: [4, 10, 22]
    

提交回复
热议问题