List comprehension for running total

前端 未结 13 1342
感动是毒
感动是毒 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:40

    If you can use numpy, it has a built-in function named cumsum that does this.

    import numpy
    tot = numpy.cumsum(a)  # returns a numpy.ndarray
    tot = list(tot)        # if you prefer a list
    

提交回复
热议问题