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