Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension for running total

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(20)  runningTotal = [] for n in range(len(a)):     new = runningTotal[n-1] + a[n] if n > 0 else a[n]     runningTotal.append(new)  # This one is a syntax error # runningTotal = [a[n] for n in range(len(a)) if n == 0 else runningTotal[n-1] + a[n]]  for i in zip(a, runningTotal):     print "{0:>3}{1:>5}".format(*i) 

yields

  0    0   1    1   2    3   3    6   4   10   5   15   6   21   7   28   8   36   9   45  10   55  11   66  12   78  13   91  14  105  15  120  16  136  17  153  18  171  19  190 

As you can see, I initialize an empty list [], then append() in each loop iteration. Is there a more elegant way to this, like a list comprehension?

like image 870
Kit Avatar asked Aug 08 '10 02:08

Kit


People also ask

How do you explain a running total?

A running total is the cumulative sum of a value and all previous values in the column. For example, imagine you are in sales and storing information about the number of items sold on a particular day. You might want to calculate a running total, the total number of items sold up to a specific date.

How do you do a cumulative sum list in Python?

We declare an empty list cum_list to which we will append elements to form the cumulative sum list. Initialize a sum variable sm=0. Start iterating over the input list, with each iteration we increment the sum value to previous value+ the current element. On each iteration, the sum value is appended to the cum_list.


2 Answers

A list comprehension has no good (clean, portable) way to refer to the very list it's building. One good and elegant approach might be to do the job in a generator:

def running_sum(a):   tot = 0   for item in a:     tot += item     yield tot 

to get this as a list instead, of course, use list(running_sum(a)).

like image 94
Alex Martelli Avatar answered Sep 28 '22 05:09

Alex Martelli


If you can use numpy, it has a built-in function named cumsum that does this.

import numpy as np tot = np.cumsum(a)  # returns a np.ndarray tot = list(tot)     # if you prefer a list 
like image 34
Mr Fooz Avatar answered Sep 28 '22 04:09

Mr Fooz