Rolling or sliding window iterator?

后端 未结 23 1845
南方客
南方客 2020-11-21 05:23

I need a rolling window (aka sliding window) iterable over a sequence/iterator/generator. Default Python iteration can be considered a special case, where the window length

23条回答
  •  梦如初夏
    2020-11-21 06:09

    a slightly modified version of the deque window, to make it a true rolling window. So that it starts being populated with just one element, then grows to it's maximum window size, and then shrinks as it's left edge comes near the end:

    from collections import deque
    def window(seq, n=2):
        it = iter(seq)
        win = deque((next(it, None) for _ in xrange(1)), maxlen=n)
        yield win
        append = win.append
        for e in it:
            append(e)
            yield win
        for _ in xrange(len(win)-1):
            win.popleft()
            yield win
    
    for wnd in window(range(5), n=3):
        print(list(wnd))
    

    this gives

    [0]
    [0, 1]
    [0, 1, 2]
    [1, 2, 3]
    [2, 3, 4]
    [3, 4]
    [4]
    

提交回复
热议问题