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

4 Answers

2
user1147618 On Best Solutions

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))
3
Aran-Fey On

Just write your own windowed function:

def windowed(iterable, size, fillvalue=None, step=1):
    for i in range(0, len(iterable), step):
        window = iterable[i:i+size]
        window += [fillvalue] * (size - len(window))
        yield window
>>> list(windowed([0,1,2,3,4], 4, fillvalue=0, step=2))
[[0, 1, 2, 3], [2, 3, 4, 0], [4, 0, 0, 0]]
3
hiro protagonist On

this should also work with iterables and not just sequences:

from itertools import islice

def sliding_window(seq, n, step, fillvalue=None):
    it = iter(seq)
    values = tuple(islice(it, n))
    while values:
        yield values + (n-len(values)) * (fillvalue, )
        values = values[step:] + tuple(islice(it, step))

the function outputs:

print(list(sliding_window(seq, n, step, fillvalue=0)))
# [(0, 1, 2, 3), (2, 3, 4, 0), (4, 0, 0, 0)]

most of it is borrowed from the original itertools recipe for a sliding window.

0
pylang On

Consider more_itertools.stagger:

Given

import itertools as it

import more_itertools as mit


iterable = [0, 1, 2, 3, 5]

Code

Get all results from sliding windows:

windows = list(mit.stagger(iterable, offsets=(0, 1, 2, 3), longest=True, fillvalue=0))
windows
# [(0, 1, 2, 3), (1, 2, 3, 5), (2, 3, 5, 0), (3, 5, 0, 0), (5, 0, 0, 0)]

Next, filter out the desired results:

[w for i, w in enumerate(windows) if not (i % 2)]
# [(0, 1, 2, 3), (2, 3, 5, 0), (5, 0, 0, 0)]

or slice the iterable:

list(it.islice(windows, 0, None, 2))
# [(0, 1, 2, 3), (2, 3, 5, 0), (5, 0, 0, 0)]