Let's say we have the list
L = ['a', '!b', '!c', 'd', 'e', '!f', 'g', 'h']
and we want to concatenate each element with the previous one if it starts with !.
Expected output:
M = ['a!b!c', 'd', 'e!f', 'g', 'h']
This works but it's probably unnecessarily complex to join the list into a string, and then to re-split the string into a list:
M = ''.join(('' if l.startswith('!') else '\n') + l for l in L).splitlines()[1:]
# ['a!b!c', 'd', 'e!f', 'g', 'h']
Is there a simpler way to concatenate elements from a list based on a criteria ('!' in l)?