Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Group element of a list in PYTHON

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']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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']]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading