List comprehension for running total

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

    Here's a linear time solution one liner:

    list(reduce(lambda (c,s), a: (chain(c,[s+a]), s+a), l,(iter([]),0))[0])
    

    Example:

    l = range(10)
    list(reduce(lambda (c,s), a: (chain(c,[s+a]), s+a), l,(iter([]),0))[0])
    >>> [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
    

    In short, the reduce goes over the list accumulating sum and constructing an list. The final x[0] returns the list, x[1] would be the running total value.

提交回复
热议问题