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

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

    First, you want a running list of subsequences:

    subseqs = (seq[:i] for i in range(1, len(seq)+1))
    

    Then you just call sum on each subsequence:

    sums = [sum(subseq) for subseq in subseqs]
    

    (This isn't the most efficient way to do it, because you're adding all of the prefixes repeatedly. But that probably won't matter for most use cases, and it's easier to understand if you don't have to think of the running totals.)

    If you're using Python 3.2 or newer, you can use itertools.accumulate to do it for you:

    sums = itertools.accumulate(seq)
    

    And if you're using 3.1 or earlier, you can just copy the "equivalent to" source straight out of the docs (except for changing next(it) to it.next() for 2.5 and earlier).

提交回复
热议问题