Home > Backend Development > Python Tutorial > How Can I Efficiently Implement Sliding Window Iteration in Python?

How Can I Efficiently Implement Sliding Window Iteration in Python?

DDD
Release: 2024-12-29 02:37:09
Original
236 people have browsed it

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
Copy after login

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
Copy after login

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])
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template