Another itertool function?

Alex Martelli aleax at aleax.it
Tue Apr 29 18:23:47 EDT 2003


Steven Taschuk wrote:

> Quoth Alex Martelli:
>> Raymond Hettinger wrote:
>>    ...
>> > Here's another idea that was submitted:
>> > 
>> > def windowed(iterable, group=2):
>> >     "returns (i[0], i[1], ... i[group-1]), (i[1], i[2], ... i[group]),
>> 
>> I think this would be perfect if the overlap between successively
>> returned windows was also a parameter, rather than being fixed to 1.
> 
> Alexander Schmolck proposed such a function back in February [1];
> his version included a "step" argument doing what you suggest.
> 
> In the discussion of whether such a function was useful enough to
> be included in itertools, I provided several use cases [2], but
> was unable to find a convincing one which needed a step other than
> one.  Do you have one in mind?

Simplest example: I have a flat sequence k1 v1 k2 v3 k3 v3 ... and I
want a mapping k1->v1, k2->v2 etc.  dict(windowed(x, 2, 2)) would do it.

Second example: if I have a sequence of daily earnings and I want a "moving 
daily average" -- for each day, the average of the seven days centered on
it -- imap(sum, windowed(earnings, 7)) would suffice [ok, sum is not the
same as avg, but dividing each number by 7 ain't hard if needed].  But say
I want a "moving weekly average" instead -- for each WEEK, the average
(or sum) of the three weeks centered on it.  Why not:
imap(sum, windowed(earnings, 21, 7)) -- it seems simplest. Or maybe faster:
imap(sum, windowed(imap(sum, windowed(earnings, 7, 7)), 3)).

In general, 1 and N are going to be the most popular 'steps' for a
window of length N, but other values may help for moving averages &c.


Alex






More information about the Python-list mailing list