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

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

    Somewhat hacky, but seems to work:

    def cumulative_sum(l):
      y = [0]
      def inc(n):
        y[0] += n
        return y[0]
      return [inc(x) for x in l]
    

    I did think that the inner function would be able to modify the y declared in the outer lexical scope, but that didn't work, so we play some nasty hacks with structure modification instead. It is probably more elegant to use a generator.

提交回复
热议问题