Search code examples
pythonlistiterationalternate

Python: How to alternate selection if first item of list element changes?


I couldn't find an algorithm to solve this simple problem:

a list:

  lista:  [[1,a],[1,b],[1,a],[2,s],[2,r],[3,e],[3,k],[3,t],[3,y]....]

I'm iterating over this list, for iterations where first item of inner list is same with next iterarion, alternate between x and y

[1,a] --> x
[1,b] --> x
[1,a] --> x
[2,s] --> y
[2,r] --> y
[3,e] --> x
[3,k] --> x
[3,t] --> x
[3,y] --> x

Solution

  • lista = [[1,'a'],[1,'b'],[1,'a'],[2,'s'],[2,'r'],[3,'e'],[3,'k'],[3,'t'],[3,'y']]
    
    >>> last_a = None
    >>> toggle = 'y'
    >>> for a, b in lista:
    ...     if last_a != a:
    ...         toggle = 'x' if toggle != 'x' else 'y'
    ...         last_a = a
    ...     print(a, b, toggle)
    ... 
    (1, 'a', 'x')
    (1, 'b', 'x')
    (1, 'a', 'x')
    (2, 's', 'y')
    (2, 'r', 'y')
    (3, 'e', 'x')
    (3, 'k', 'x')
    (3, 't', 'x')
    (3, 'y', 'x')