time series calculation in list comprehension?

johnzenger at gmail.com johnzenger at gmail.com
Fri Mar 10 13:51:35 EST 2006


falcon wrote:
> Is there a way I can do time series calculation, such as a moving
> average in list comprehension syntax?  I'm new to python but it looks
> like list comprehension's 'head' can only work at a value at a time.  I
> also tried using the reduce function and passed in my list and another
> function which calculates a moving average outside the list comp. ...
> but I'm not clear how to do it.  Any ideas?  Thanks.

I agree with others that reduce is not the best way to do this.  But,
to satisfy your curiosity, I offer this horribly inefficient way to use
"reduce" to calculate the average of a list:

from __future__ import division

def reduceaverage(acc, x):
    return [acc[0] + x, acc[1] + 1, (acc[0] + x) / (acc[1] + 1) ]

numbers = [4, 8, 15, 16, 23, 42]
print reduce(reduceaverage, numbers, [0,0,0])[2]

...basically, the idea is to write a function that takes as its first
argument the accumulated values, and as its second argument the next
value in the list.  In Python, this is almost always the wrong way to
do something, but it is kind of geeky and LISP-ish.




More information about the Python-list mailing list