pythonfunctionpython-itertoolswindowed

Sliding window of width n over the given iterable


I have a sequence, window size and step:

seq = [0,1,2,3,4]
n=4
step=2

from more_itertools import windowed
list(windowed([0,1,2,3,4], n, fillvalue=0, step=step))

result:

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

but I need:

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

Please help me find a solution


Solution

  • How about using padded?

    seq = [0,1,2,3,4]
    n=4
    step=2
    
    from more_itertools import windowed, padded
    list(windowed(padded(seq, 0, n=n, next_multiple=True), n, step=step))