Home >Backend Development >Python Tutorial >How Can I Efficiently Implement a Rolling or Sliding Window Iterator in Python?

How Can I Efficiently Implement a Rolling or Sliding Window Iterator in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-17 22:21:23953browse

How Can I Efficiently Implement a Rolling or Sliding Window Iterator in Python?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn