Skip to content
Advertisement

Iterate over n successive elements of list (with overlapping)

The itertools python module implements some basic building blocks for iterators. As they say, “they form an iterator algebra”. I was expecting, but I could not find a succinctly way of doing the following iteration using the module. Given a list of ordered real numbers, for example

JavaScript

… return a new list (or just iterate) grouping by some n value, say 2

JavaScript

The way I found of doing this was as follows. First split the list in two, with evens and odds indexes:

JavaScript

Then construct the new list:

JavaScript

In essence, it is similar to a moving mean.

Is there a succinctly way of doing this (with or without itertools)?


PS.:

Application

Imagine the a list as the set of timestamps of some events occurred during an experiment:

JavaScript

This code is being used to segment those events in accord with different temporal windows. Right now I am interested in the data between 2 successive events; ‘n > 2’ would be used only for exploratory purposes.

Advertisement

Answer

For 2, you can just do

JavaScript

For fixed n, the technique is similar:

JavaScript

For variable n, you could zip a variable number of slices, or (especially if the window size is close to the size of a) you could use slicing to take windows directly:

JavaScript

If a is not a list, you could generalize the pairwise recipe from the itertools docs:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement