List comprehension for running total

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

    I'm not sure about 'elegant', but I think the following is much simpler and more intuitive (at the cost of an extra variable):

    a = range(20)
    
    runningTotal = []
    
    total = 0
    for n in a:
      total += n
      runningTotal.append(total)
    

    The functional way to do the same thing is:

    a = range(20)
    runningTotal = reduce(lambda x, y: x+[x[-1]+y], a, [0])[1:]
    

    ...but that's much less readable/maintainable, etc.

    @Omnifarous suggests this should be improved to:

    a = range(20)
    runningTotal = reduce(lambda l, v: (l.append(l[-1] + v) or l), a, [0])
    

    ...but I still find that less immediately comprehensible than my initial suggestion.

    Remember the words of Kernighan: "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it."

提交回复
热议问题