Rolling or Sliding Window Iterator
Rolling or sliding window iterators enable the traversal of a sequence in overlapping windows of a specified size. Iterating over a sequence with a window size of 1 is essentially the default Python iteration.
Efficient and Elegant Implementation
The following implementation from the Python documentation leverages the itertools module for increased efficiency:
from itertools import islice def window(seq, n=2): """Returns a sliding window (of width n) over data from the iterable""" "s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ..." it = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result for elem in it: result = result[1:] + (elem,) yield result
Implementation for Simple Iterables
For iterables represented as simple lists or tuples, a straightforward approach involves iterating through the iterable with the specified window size:
seq = [0, 1, 2, 3, 4, 5] window_size = 3 for i in range(len(seq) - window_size + 1): print(seq[i: i + window_size])
Output:
[0, 1, 2] [1, 2, 3] [2, 3, 4] [3, 4, 5]
The above is the detailed content of How Can I Efficiently Implement a Rolling or Sliding Window Iterator in Python?. For more information, please follow other related articles on the PHP Chinese website!