Search code examples
pythonlist

Python group by adjacent items in a list with same attributes


Please see the simplified example:

A = [(721,'a'),(765,'a'),(421,'a'),(422,'a'),(106,'b'),(784,'a'),(201,'a'),(206,'b'),(207,'b')]

I want group adjacent tuples with attribute 'a', every two pair wise and leave tuples with 'b' alone.

So the desired tuple would looks like:

A = [[(721,'a'),(765,'a')],
     [(421,'a'),(422,'a')],
     [(106,'b')],
     [(784,'a'),(201,'a')],
     [(206,'b')],
     [(207,'b')]]

What I can do is to build two separated lists contains tuples with a and b.

Then pair tuples in a, and add back. But it seems not very efficient. Any faster and simple solutions?


Solution

  • Assuming a items are always in pairs, a simple approach would be as follows.

    Look at the first item - if it's an a, use it and the next item as a pair. Otherwise, just use the single item. Then 'jump' forward by 1 or 2, as appropriate:

    A=[(721,'a'),(765,'a'),(421,'a'),(422,'a'),(106,'b'),(784,'a'),(201,'a'),(206,'b'),(207,'b')]
    
    result = []
    count = 0
    while count <= len(A)-1:
        if A[count][1] == 'a':
            result.append([A[count], A[count+1]])
            count += 2
        else:
            result.append([A[count]])
            count += 1
    
    print(result)