List comprehension for running total

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

    This can be implemented in 2 lines in Python.

    Using a default parameter eliminates the need to maintain an aux variable outside, and then we just do a map to the list.

    def accumulate(x, l=[0]): l[0] += x; return l[0];
    map(accumulate, range(20))
    

提交回复
热议问题