user6038900
user6038900

Reputation:

Loop through array as four elements but in a consecutive fashion

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

Answers (3)

mad_
mad_

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

pault
pault

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

Netwave
Netwave

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

Related Questions