user3671704
user3671704

Reputation: 161

Iterate through pairs in a Python list and update the pairs during the iteration

Hi I am trying to make a code that iterates over pair in a list and updates the pair if condition fulfil

List=[A1,A2,A4,A5,E3,A3,E1,A7,E2,E3]

This is what I have so far:

def pairwise(ListX):
"Pairs -> (A1,A2), (A2,A4), (A4, A5),(A5, E3),(E3, A3),(A3, E1), ..."
a, b = tee(ListX)
next(b, None)
return izip(a, b)

for a, b in pairwise(List):
  if a!= b and a == 'E':
   do something and switch positions

In this case, the pair (E3, A3) will be switched and the new order will be ( A3,E3) and then the new pair to iterate will be will be: (E3, E1) and not (A3, E1). The code I have so far make the action and switch the order of the list:

    List=[A1,A2,A4,A5,E3,A3,E1,A7,E2,E3] <--Initial
    List=[A1,A2,A4,A5,A3,E3,E1,A7,E2,E3]  <--Switched

However after the switch keep iterating on the pair (A3, E1).

Any suggestions?

Upvotes: 0

Views: 536

Answers (2)

DiA
DiA

Reputation: 369

I think there is no reason to use pairwise function because it's return new object.

l = ['A1', 'A2', 'A4', 'A5', 'E3', 'A3', 'E1', 'A7', 'E2', 'E3']
for i in range(len(l)-1):
    if l[i] != l[i+1] and l[i][:1] == 'E':
        l[i], l[i+1] = l[i+1], l[i]
        break
print(l)

If you remove break next pair be ('E3', 'E1')

Upvotes: 1

Blckknght
Blckknght

Reputation: 104712

Your code doesn't work because of how itertools.tee is implemented. Because it works on arbitrary iterators (not only sequences), it needs to store the values yielded by one of the iterators but not by the other.

You can work around this though, since you're actually calling your pairwise function on a list, which you can independently iterate over multiple times.

def pairwise(ListX):
    a = iter(ListX)
    b = iter(ListX)
    next(b, None)
    return izip(a, b)

Now, if you modify ListX while iterating over the pairs, the updates will always be seen.

Note that to do your modifications efficiently, you might want to use enumerate to get an index along with the pair values.

Upvotes: 1

Related Questions