Home >Backend Development >Python Tutorial >How Can I Efficiently Implement Sliding Window Iteration in Python?
Sliding Window Iteration Techniques
For sliding window iteration over an iterable, a basic implementation can use list slicing and iteration:
def rolling_window(seq, window_size): it = iter(seq) win = [it.next() for cnt in range(window_size)] # First window yield win for e in it: # Subsequent windows win[:-1] = win[1:] win[-1] = e yield win
Efficient and Elegant Solutions
For greater efficiency and elegance, a generator expression with itertools can be employed:
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
For simpler iterables like lists or tuples, a straightforward approach using range and indexing 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])
The above is the detailed content of How Can I Efficiently Implement Sliding Window Iteration in Python?. For more information, please follow other related articles on the PHP Chinese website!