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

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

    Assignment expressions from PEP 572 (new in Python 3.8) offer yet another way to solve this:

    time_interval = [4, 6, 12]
    
    total_time = 0
    cum_time = [total_time := total_time + t for t in time_interval]
    

提交回复
热议问题