List comprehension for running total

前端 未结 13 1358
感动是毒
感动是毒 2020-12-05 02:47

I want to get a running total from a list of numbers.

For demo purposes, I start with a sequential list of numbers using range

a = range         


        
13条回答
  •  我在风中等你
    2020-12-05 03:35

    Another one-liner, in linear time and space.

    def runningSum(a):
        return reduce(lambda l, x: l.append(l[-1]+x) or l if l else [x], a, None)
    

    I'm stressing linear space here, because most of the one-liners I saw in the other proposed answers --- those based on the pattern list + [sum] or using chain iterators --- generate O(n) lists or generators and stress the garbage collector so much that they perform very poorly, in comparison to this.

提交回复
热议问题