groupby
. comp, , .;) () , ( , .join
).
We use bool
as a key function, so the groups are either true or false. The false-ish group is a group of empty lines, so we expand the list of results new
using the group. The true group contains only non-empty lines, so we append it and add the result to new
.
from itertools import groupby
old = ['abc', 'retro', '', '', 'images', 'cool', '', 'end']
new = []
for k, g in groupby(old, key=bool):
if k:
new.append(' '.join(g))
else:
new.extend(g)
print(new)
Exit
['abc retro', '', '', 'images cool', '', 'end']
source
share