Home > Net >  Group element of a list in PYTHON
Group element of a list in PYTHON

Time:01-12

I have a list like this i want to groupe every 2 elements if they have the same string.split('#',1) and string.split('#',2) `

list_1 = ['PERSONNE#FAVE#12','PERSONNE#DATE#12','PERSONNE#KIAL#12']
list_2 = ['PERSONNE#FAVE#11','PERSONNE#DATE#10']
sortie_list = list_1   list_2

Output desired: if an element has not a similar string it will be append the out_list

out_list= [['PERSONNE#FAVE#12','PERSONNE#FAVE#11'],  ['PERSONNE#DATE#12','PERSONNE#DATE#10'],'PERSONNE#KIAL#12']

CodePudding user response:

itertools.groupby is the ticket. You just have to remember to sort first.

>>> from itertools import groupby
>>> f = lambda x: x.split('#', 2)[0:2]
>>> [list(v) for _, v in groupby(sorted(sortie_list, key=f), key=f)]
[['PERSONNE#DATE#12', 'PERSONNE#DATE#10'], ['PERSONNE#FAVE#12', 'PERSONNE#FAVE#11'], ['PERSONNE#KIAL#12']]

CodePudding user response:

Can be done using defaultdict from collections.

from collections import defaultdict

sortie_list = list_1   list_2

out_list = defaultdict(list)

for item in sortie_list:
    first, second, third = item.split("#")
    out_list[first '#' second].append(item)

out_list = list(out_list.values())

With these inputs:

list_1 = ['PERSONNE#FAVE#12','PERSONNE#DATE#12','PERSONNE#KIAL#12']
list_2 = ['PERSONNE#FAVE#11','PERSONNE#DATE#10']

The output is:

[['PERSONNE#FAVE#12', 'PERSONNE#FAVE#11'], ['PERSONNE#DATE#12', 
'PERSONNE#DATE#10'], 'PERSONNE#KIAL#12']
  • Related