Suppose I have the following list:
>>> my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I want to write a function that will iterate over slices of n
elements to the left and right of each item of this list:
def sliding_window_n_elements_left_and_right(lst, n):
...
The function should work like this:
>>> list(sliding_window_n_elements_left_and_right(my_list, 0))
[[0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10]]
>>> list(sliding_window_n_elements_left_and_right(my_list, 1))
[[0, 1], [0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10]]
>>> list(sliding_window_n_elements_left_and_right(my_list, 2))
[[0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10], [8, 9, 10]]
Thank you for your time and skill!