移动窗口列表

发布于 2025-02-08 07:43:20 字数 929 浏览 2 评论 0原文

假设我有列表[1,2,2,2,3,4,5,6,7]我需要产生输出(移动窗口):

0  1
8  2
16 3
24 4
32 5

0  2
8  3
16 4
24 5
32 6

0  3
8  4
16 5
24 6
32 7

0  1
8  2
16 3
24 4
32 5

当5圈高窗口到达列表的最后一个元素时(这里7)我们需要开始1,我需要像i * 8一样生成第一列。

我带来了这样的东西(但不是完全):

def w(l):
    global lines
    for i in range(lines - 1, lines + 4):
        location = (i % 5) * 8
        print(f'{location} {l[i]}')
        if lines >= len(l) - 4:
            lines = 1


if __name__ == '__main__':
    ll = [1, 2, 3, 4, 5, 6, 7]
    for i in range(1, 4):
        lines = i
        print(f'-- {i} --')
        w(ll)

输出是:

-- 1 --
0 1
8 2
16 3
24 4
32 5
-- 2 --
8 2
16 3
24 4
32 5
0 6
-- 3 --
16 3
24 4
32 5
0 6
8 7

也许Deque是答案吗?

Let say I have list [1, 2, 3, 4, 5, 6, 7] I need produce output like (moving window):

0  1
8  2
16 3
24 4
32 5

0  2
8  3
16 4
24 5
32 6

0  3
8  4
16 5
24 6
32 7

0  1
8  2
16 3
24 4
32 5

when 5-row-height window get to last element of list (7 here) we need start 1, and I need first column be generated like i * 8.

I came with something like this (but not quite):

def w(l):
    global lines
    for i in range(lines - 1, lines + 4):
        location = (i % 5) * 8
        print(f'{location} {l[i]}')
        if lines >= len(l) - 4:
            lines = 1


if __name__ == '__main__':
    ll = [1, 2, 3, 4, 5, 6, 7]
    for i in range(1, 4):
        lines = i
        print(f'-- {i} --')
        w(ll)

Output is:

-- 1 --
0 1
8 2
16 3
24 4
32 5
-- 2 --
8 2
16 3
24 4
32 5
0 6
-- 3 --
16 3
24 4
32 5
0 6
8 7

Maybe deque is an answer?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

软甜啾 2025-02-15 07:43:20

要修复位置零件,您只需添加枚举并用8次乘以。

def w(l):
    global lines
    for p,i in enumerate(range(lines - 1, lines + 4)):
        location = p * 8
...

To fix the location part, you can just add enumerate and multiply with 8.

def w(l):
    global lines
    for p,i in enumerate(range(lines - 1, lines + 4)):
        location = p * 8
...

瀞厅☆埖开 2025-02-15 07:43:20

您可以使用numpy:

import numpy as np
sliding_window = np.lib.stride_tricks.sliding_window_view([1, 2, 3, 4, 5, 6, 7], 5)
for i in sliding_window:
    for j, k in enumerate(i):
        print(j*8, k)

输出:

0 1
8 2
16 3
24 4
32 5
0 2
8 3
16 4
24 5
32 6
0 3
8 4
16 5
24 6
32 7

You can use sliding_window_view() from numpy:

import numpy as np
sliding_window = np.lib.stride_tricks.sliding_window_view([1, 2, 3, 4, 5, 6, 7], 5)
for i in sliding_window:
    for j, k in enumerate(i):
        print(j*8, k)

Output:

0 1
8 2
16 3
24 4
32 5
0 2
8 3
16 4
24 5
32 6
0 3
8 4
16 5
24 6
32 7
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文