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

Question:

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.

Thank you!

Asked By: LD-DS-00

||

Answers:

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

Answered By: mozway
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.