Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A list of sliding windows over a list

Tags:

python

slice

I have a list of length L

In [92]: li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

and I know how I can generate N overlapping sub-lists

In [93]: L, N = 10, 4                                                                     

In [94]: [li[i:L-N+1+i] for i in range(N)]                                                
Out[94]: 
[[1, 2, 3, 4, 5, 6, 7],
 [2, 3, 4, 5, 6, 7, 8],
 [3, 4, 5, 6, 7, 8, 9],
 [4, 5, 6, 7, 8, 9, 10]]

On the other hand I don't know how to obtain the same result without using L

In [95]: [li[i:i-N+1] for i in range(N)]                                                  
Out[95]: [[1, 2, 3, 4, 5, 6, 7], [2, 3, 4, 5, 6, 7, 8], [3, 4, 5, 6, 7, 8, 9], []]

short of using i-N+1 if i-N+1 else None as the second part of the slice specification.

Is it possible to obtain my list of sub-lists w/o using L and w/o a conditional?

like image 203
gboffi Avatar asked Dec 11 '25 15:12

gboffi


1 Answers

Cheeky boolean abuse:

li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
N = 4
lsts = [li[i:(i-N+1 or None)] for i in range(N)]
print(*lsts, sep='\n')
# [1, 2, 3, 4, 5, 6, 7]
# [2, 3, 4, 5, 6, 7, 8]
# [3, 4, 5, 6, 7, 8, 9]
# [4, 5, 6, 7, 8, 9, 10]
like image 195
jdehesa Avatar answered Dec 13 '25 04:12

jdehesa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!