How can I implement this kind of iteration similar to sliding window method in python.
Given s = [1, 2, 3, 4, 5, 6]
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6]
[6]
In programming, we use lists to store sequences of related data. We often want to perform the same operation on every element in a list, like displaying each element or manipulating them mathematically. To do that, we can use a loop to iterate over each element, repeating the same code for each element.
We can iterate through a list by using the range() function and passing the length of the list. It will return the index from 0 till the end of the list. The output would be the same as above.
Implement Sliding Window Using GeneratorsThe yield keyword inside a function determines that the function is a generator. This will return a generator object and you could either call next(object) to get the next value or iterator in a for loop.
l = [1, 2, 3, 4, 5, 6]
for i in range(len(l)):
print l[i : i+3]
Output
[1, 2, 3]
[2, 3, 4]
[3, 4, 5]
[4, 5, 6]
[5, 6]
[6]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With