List comprehension for running total

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

    Use itertools.accumulate(). Here is an example:

    from itertools import accumulate
    
    a = range(20)
    runningTotals = list(accumulate(a))
    
    for i in zip(a, runningTotals):
        print "{0:>3}{1:>5}".format(*i)
    

    This only works on Python 3. On Python 2 you can use the backport in the more-itertools package.

提交回复
热议问题