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

How can I merge list items that are between spaces? – Python

How can I merge list items that are between spaces in a list. For examples:

lst = ['a a a',' ', ' ', ' ', 'b b b','c c c','d d d', ' ',' ', 'e e','f', ' ', 'g']

To this:

new_list = ['a a a', 'b b b c c c d d d', 'e e f', 'g']

I seem not to be able to work out the logic in my code.

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

Thank you!

>Solution :

Use itertools.groupby in a list comprehension and str.join:

from itertools import groupby

lst = ['a',' ', ' ', ' ', 'b','c','d', ' ',' ', 'e','f',' ', 'g']

new_list = [''.join(g) for k, g in groupby(lst, lambda x: x!=' ') if k]

output: ['a', 'bcd', 'ef', 'g']

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