Reputation:
Im using the following code to loop through an array.
arr = [1 ,2 ,3 ,4 ,5 , 6,7]
for a, b, c in zip(*[iter(arr)]*3):
print (a, b, c)
It retrieves the output in two parts as (1,2,3) and (4,5,6)
However I want the output to be consecutive in the sense (1,2,3),(2,3,4),(3,4,5),(4,5,6),(5,6,7) but also in a faster way. Is there any other way apart from iter to achieve this?
Upvotes: 4
Views: 579
Reputation: 8273
from toolz.itertoolz import sliding_window
arr = [1 ,2 ,3 ,4 ,5 , 6,7]
list(sliding_window(3,arr))
Output
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7)]
Upvotes: 2
Reputation: 43504
You can also loop over slices of size n
n = 3
for a, b, c in [arr[i:i+n] for i in range(len(arr)-(n-1))]:
print(a, b, c)
#1 2 3
#2 3 4
#3 4 5
#4 5 6
#5 6 7
Upvotes: 3
Reputation: 42736
Just use slicing:
>>> l = list(range(10))
>>> list(zip(l, l[1:], l[2:]))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9)]
It will be even better if you use itertools.islice
>>> from itertools import islice
>>> list(zip(l, islice(l, 1, None), islice(l, 2, None)))
[(0, 1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9)]
Upvotes: 3