Home >Backend Development >Python Tutorial >How Can I Create a Sliding Window Iterator in Python?
Sliding Window Iterators in Python
When working with streaming data or sequential processing, a rolling or sliding window iterator can be invaluable for examining a stream of elements in a defined window.
In Python, you can create a sliding window iterator using the built-in itertools module. The window() function from an older version of the Python documentation provides a concise and efficient implementation:
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
Alternatively, for a simple list or tuple, a straightforward approach can be used:
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])
In both cases, the window slides through the sequence, producing overlapping windows of specified size, making it easy to analyze and process data in a manageable manner.
The above is the detailed content of How Can I Create a Sliding Window Iterator in Python?. For more information, please follow other related articles on the PHP Chinese website!