Moving window thru list

Viewed 49

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?

2 Answers

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

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
Related