在数字序列上滑动窗口

时间:2017-06-02 23:48:13

标签: python python-3.x sliding-window

我正在尝试构建一个滑动窗口方法,该方法将滑过列表中元素的数字序列。这很重要,我相信,与SO中的其他滑动窗口方法不同,幻灯片通常在列表的索引上进行。

我的意思是如下所示。拥有整数列表

li = [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

使用window=3step=2,预期输出为:

[1, 3]
[3, 4, 5]
[5, 6, 7]
[7, 8, 9]
[9, 10, 11]
[11, 12]

到目前为止我的代码:

window = 3
step = 2

last_pos = 0
w_start = 1
w_end = window
next_start = w_start + step
dat = []  # values for window
next_dat = []  # values for the next window

li = [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

for e in li:
    ipos = int(e)
    if ipos > last_pos:
        dat.append(ipos)

        if ipos == w_end:  # end of window
            w_start += step
            w_end += step
            print(dat)
            dat = next_dat  # reset window...

        if ipos >= next_start:  # ipos is in the next window
            next_dat.append(ipos)

        if w_start == next_start:  # move next window
            next_start += step
            next_dat = []  # reset next window...
    else:
        raise Exception('List is not sorted')

    last_pos += 1

# the last window if not empty
print(dat) if dat else 'false'

输出是预期的:

[1, 3]
[3, 4, 5]
[5, 6, 7]
[7, 8, 9]
[9, 10, 11]
[11, 12]

然而,除了不太优雅之外,当两个以上的窗口重叠时,这段代码似乎失败了。例如,使用window=5step=2会产生错误的输出:

[1, 3, 4, 5]
[3, 4, 5, 6, 7]
[6, 7, 8, 9]
[8, 9, 10, 11]
[10, 11, 12]

第1和第2个窗口都没问题,但从第3个开始,事情变得混乱。例如,第三个窗口应该从5开始,并且应该有5个元素,而不是4个元素。我的目标是改为使用以下窗口:

[1, 3, 4, 5]
[3, 4, 5, 6, 7]
[5, 6, 7, 8, 9]
[7, 8, 9, 10, 11]
[9, 10, 11, 12]

有关如何解决此问题的任何想法?

请注意,它不是列表索引,但列表值自行滑动。我相信这两种方法在列表中缺少某些值的特定情况下是不同的。在上面显示的情况中,列表中的前三项是1, 3, 4。我认为迭代索引(window=2step=2)将导致以下输出(但未经过测试):

[1, 3]
[4]

而我想要做的是迭代列表的值,以便生成的窗口为:

[1]
[3, 4]

因此,第一个窗口中缺少值2,因为它不在原始列表中。

虽然这里有一个列表,但最后我会想要从一个难以适应内存的大文件中读取这些内容。

1 个答案:

答案 0 :(得分:0)

问题中代码的问题在于,您不确定需要预先跟踪多少个窗口。 此任务的最佳方法可能只使用一个窗口列表,然后复制那些与下一个窗口重叠的值,依此类推。

以下代码适用于我测试过的所有窗口:

window = 3
step = 2

last_pos = 0
w_start = 1
w_end = window
dat = []  # values for window
next_dat = []  # values for the next window

li = [1, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

for e in li:
    ipos = int(e)
    if ipos > last_pos:

        if ipos > w_end:  # end of window
            print(dat)
            w_start += step
            w_end += step

            if step == window:  # non-overlapping
                next_dat = []  # reset next window...
            else:
                next_dat = [x for x in dat if x >= (w_start)]

            dat = next_dat  # reset window...

        dat.append(ipos)
    else:
        raise Exception('List is not sorted')

    last_pos += 1

# the last window if not empty
print(dat) if dat else 'false'

(window = 3 and step = 2)

[1, 3]
[3, 4, 5]
[5, 6, 7]
[7, 8, 9]
[9, 10, 11]
[11, 12]

(window = 2 and step = 2)

[1]
[3, 4]
[5, 6]
[7, 8]
[9, 10]
[11, 12]

(窗口= 5,步骤= 2)

[1, 3, 4, 5]
[3, 4, 5, 6, 7]
[5, 6, 7, 8, 9]
[7, 8, 9, 10, 11]
[9, 10, 11, 12]

同样,我认为这段代码并不是很优雅,但是它完成了这项工作,所以我将这个答案标记为已被接受。但是,我仍然对此代码的任何改进/建议持开放态度。