Home > Mobile >  Iterate on a list with a window
Iterate on a list with a window

Time:09-24

let say we have this list : L =[1,2,3, 4, 5, 6, 7, 8 ... n] we want to have this result by a window of 3 elements form the list :

l1=[1,2,3]
l2=[2,3,4]
l3=[3,4,5]
l4=[4,5,6]
l6=[5,6,7]
l7=[6,7,8]

.... until we iterate over the array, and each previous array is stored in a final array, so we end up with this:

final_array= [ [1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7],[6,7,8] ]

how could we do this easily with a lambda function ?

CodePudding user response:

Here is one of the approaches:

L =[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
out = []
window_size = 3
if (window_size>len(L)):
    print ('Window Size is more than the list size')
else:
    for i in range(len(L)-window_size 1):
        out.append(L[i:i window_size])
    print (out)

Output:

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

CodePudding user response:

The third-party package more_itertools has a handy function called windowed that does exactly that:

In [1]: import more_itertools

In [2]: list(more_itertools.windowed(range(1, 9), n=3))
Out[2]: [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8)]

CodePudding user response:

The easiest way to solve it would be with a list comprehension as Ch3steR pointed out in the comments:

[L[i: i window_size] for i in range(len(L) - len(L)%window_size)]; set your window_size accordingly. – Ch3steR


As for how to do it with a lambda: you can use a lambda as well and apply it onto Ch3steR'S solution:

L = list(range(20)) 

win_size = 4

# this is just "one kind of" indirection for the list comp to force
# usage of a lambda  - does not make it more clear though
lmd = lambda data, pos, wins: data[pos: pos   wins] 

print( [lmd(L, p, win_size) for p in range(len(L) - win_size   1)])

From your comment:

I tried working with cursors and got a little lost

Cursors? You can do it with iterators as well - but it will take some more code:

L = list(range(20))

win_size = 4

# generate iterators
iterators = [iter(L) for _ in range(win_size)]

# advance iterators: 0th points to 0th elem, 1st to the 1st elem, etc.
for pos, i in enumerate(iterators):
    for _ in range(pos):
        next(i)

# collect the values from the iterators - cut off when 1st iterator is exhausted
k = [ list(map(next, iterators)) for _ in range(len(L) - win_size   1)]
print(k)

to get to

[[0, 1, 2, 3], [1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7],
 [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12],
 [10, 11, 12, 13], [11, 12, 13, 14], [12, 13, 14, 15], [13, 14, 15, 16],
 [14, 15, 16, 17], [15, 16, 17, 18], [16, 17, 18, 19]]
  • Related