How do I combine the elements of a list if some condition is met.
I\'ve seen posts about combining elements of a list, but not with some condition.
Use itertools.groupby:
>>> from itertools import groupby
>>> out = []
>>> for lst in words:
d = []
for k, g in groupby(lst, lambda x: '!' in x):
if k:
d.append(', '.join(g))
else:
d.extend(g)
out.append(d)
...
>>> out
[['this', 'that!', 'riff', 'raff'],
['hip', 'hop!, flip!', 'flop'],
['humpty', 'dumpty!, professor!, grumpy!']]