oussama bousselmi
oussama bousselmi

Reputation: 105

how to group list elements having the same name?

i am trying to regroup elements having the same name,i tried this code:

l=[0,1,1,1,3,3]
lo=[[2,1,5],[2,8,9],[5,9,7],[4,6,9],[7,9,5],[2,5,6]]
ss=[]
for i in range(0,6):
    for j in range(i+1,6):
        if l[i]==l[j]:
            b=[lo[i],lo[j]]
            print(b)
            ss.append(b)
            print('////',ss)
           break

        else:
            b=[lo[i]]
            print('****',b)
            ss.append(b)
            print('/*/*/',ss)
            break

print('ss:',ss)

i expected the result

ss: [[2,1,5],[[2,8,9],[5,9,7],[4,6,9]],[[7,9,5],[2,5,6]]] 

but it gives:

ss: [[[2, 1, 5]], [[2, 8, 9], [5, 9, 7]], [[5, 9, 7], [4, 6, 9]], [[4, 6, 9]], [[7, 9, 5], [2, 5, 6]]]

Upvotes: 1

Views: 459

Answers (1)

blhsing
blhsing

Reputation: 107124

You can zip the two lists into a sequence of tuples so that you can use itertools.groupby to group the tuples based on the values from l:

from itertools import groupby
[[s for _, s in g] for _, g in groupby(zip(l, lo), lambda t: t[0])]

This returns:

[[[2, 1, 5]], [[2, 8, 9], [5, 9, 7], [4, 6, 9]], [[7, 9, 5], [2, 5, 6]]]

Upvotes: 2

Related Questions