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

前端 未结 21 1601
挽巷
挽巷 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:45

    You can calculate the cumulative sum list in linear time with a simple for loop:

    def csum(lst):
        s = lst.copy()
        for i in range(1, len(s)):
            s[i] += s[i-1]
        return s
    
    time_interval = [4, 6, 12]
    print(csum(time_interval))  # [4, 10, 22]
    

    The standard library's itertools.accumulate may be a faster alternative (since it's implemented in C):

    from itertools import accumulate
    time_interval = [4, 6, 12]
    print(list(accumulate(time_interval)))  # [4, 10, 22]
    

提交回复
热议问题