Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python group by adjacent items in a list with same attributes

Tags:

python

list

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?

like image 595
Kevin Avatar asked Aug 03 '26 18:08

Kevin


1 Answers

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)
like image 111
match Avatar answered Aug 06 '26 06:08

match