Cansisti
Cansisti

Reputation: 153

Is there any simple way in Python to pair neighboring elements in an array?

Say I've got A = [1, 2, 3, 4]
I want to have B = [(1,2), (2,3), (3,4)],
so I can check if B contains (u,v).

Already tried iterating from 0 to len(A)-1 checking every (A[i],A[i]+1) but this seems to be inefficient.

A = [1, 2, 3, 4]
for i in range(len(A)-1):
   if A[i] == u and A[i+1] == v:
      #assume true
#assume false

Having B as above would help in this problem and some others, I think.

Upvotes: 1

Views: 1512

Answers (4)

Amany
Amany

Reputation: 321

This will create the B the you are looking for

A = [1, 2, 3, 4]
B=[]
for i in range(len(A)-1):
    B.append((A[i],A[i+1]))

print(B)
#outputs: [(1, 2), (2, 3), (3, 4)]

Upvotes: 1

chepner
chepner

Reputation: 530970

zip(A, A[1:]) is nice, but has the drawback of having to virtually duplicate A first. A pair of separate iterators can be used instead.

from itertools import tee

a1, a2 = tee(A)
next(a2)
B = list(zip(a1, a2))

You can replace the call to next with a call to islice that can be inlined.

from itertools import tee, slice

a1, a2 = tee(A)
B = list(zip(a1, islice(a2, 1))

These are both a little slower (though still linear) than zipping two concrete lists, but use O(1) instead of O(n) additional memory.

Upvotes: 3

Amany
Amany

Reputation: 321

You can also use list comprehention:

B=[(A[i],A[i+1]) for i in range(len(A)-1)]

Upvotes: 2

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6920

Try this :

B = [(i,j) for i,j in zip(A, A[1:])]

OUTPUT :

[(1, 2), (2, 3), (3, 4)]

Upvotes: 4

Related Questions