Why I think range is a wart.
Magnus Lie Hetland
mlh at vier.idi.ntnu.no
Fri Mar 15 19:40:06 EST 2002
In article <mailman.1016161825.20741.python-list at python.org>,
Christian Tanzer wrote:
>
[snip]
>> It happens to me too, mostly when I'm using a sliding window
>> type algorithm, that is, I need to look at two adjacent members
>> of the list. You can't do this easily by iterating through the list;
>> unrolling the first entry and the last entry are a pain.
>
>I use a function pairwise to do such things:
>
> for l, r in pairwise(mylist) :
> <whatever>
>
>Probably not as fast as index manipulation, but IMHO much easier to
>read/write/understand.
As an apropos, I need sliding windows a bit too, and have been using
the following solution in numarray:
from numarray import *
def windows(data, size):
shape = (size, len(data)-size+1)
return data[sum(indices(shape))]
It can be used like this:
>>> print windows(arange(10), 3)
[[0 1 2]
[1 2 3]
[2 3 4]
[3 4 5]
[4 5 6]
[5 6 7]
[6 7 8]
[7 8 9]]
It took me a while to figure out exactly how to do it but figuring out
how it works shouldn't be that hard ;)
Of course these are overlapping windows (with step 1) -- a
non-overlapping version is left as an exercise for the reader <wink>.
--
Magnus Lie Hetland The Anygui Project
http://hetland.org http://anygui.org
More information about the Python-list
mailing list