List comprehension for running total

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

    I would use a coroutine for this:

    def runningTotal():
        accum = 0
        yield None
        while True:
            accum += yield accum
    
    tot = runningTotal()
    next(tot)
    running_total = [tot.send(i) for i in xrange(N)]
    

提交回复
热议问题