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

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

    A pure python oneliner for cumulative sum:

    cumsum = lambda X: X[:1] + cumsum([X[0]+X[1]] + X[2:]) if X[1:] else X
    

    This is a recursive version inspired by recursive cumulative sums. Some explanations:

    1. The first term X[:1] is a list containing the previous element and is almost the same as [X[0]] (which would complain for empty lists).
    2. The recursive cumsum call in the second term processes the current element [1] and remaining list whose length will be reduced by one.
    3. if X[1:] is shorter for if len(X)>1.

    Test:

    cumsum([4,6,12])
    #[4, 10, 22]
    
    cumsum([])
    #[]
    

    And simular for cumulative product:

    cumprod = lambda X: X[:1] + cumprod([X[0]*X[1]] + X[2:]) if X[1:] else X
    

    Test:

    cumprod([4,6,12])
    #[4, 24, 288]
    

提交回复
热议问题