给定可迭代范围上宽度为n的滑动窗口

时间:2019-04-09 10:23:40

标签: python function itertools windowed

我有一个序列,窗口大小和步骤:

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))

结果:

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

但我需要:

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

请帮助我找到解决方法

4 个答案:

答案 0 :(得分:3)

只需编写自己的windowed函数:

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]]

答案 1 :(得分:3)

这也应该与可迭代对象一起使用,而不仅仅是序列:

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))

函数输出:

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

大部分是从原始itertools配方中借来的,用于sliding window

答案 2 :(得分:2)

如何使用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 :(得分:0)

考虑more_itertools.stagger

给出

import itertools as it

import more_itertools as mit


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

代码

从滑动窗口获取所有结果:

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)]

下一步,过滤出所需的结果:

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

slice迭代:

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