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.
Here's my solution:
words = [
['this','that!','riff','raff'],
['hip','hop!','flip!','flop'],
['humpty','dumpty!','professor!','grumpy!']
]
output = []
for wl in words:
out_wl = []
bang_wl = []
for w in wl:
if '!' in w:
bang_wl.append(w)
else:
if bang_wl:
out_wl.append(','.join(bang_wl))
bang_wl = []
out_wl.append(w)
if bang_wl:
out_wl.append(','.join(bang_wl))
output.append(out_wl)
print output
[['this', 'that!', 'riff', 'raff'], ['hip', 'hop!,flip!', 'flop'], ['humpty', 'dumpty!,professor!,grumpy!']]
bang_wl
accumulates words with !
until it hits a word that doesn't contain a !
. At this point, it join
s the words in bang_wl
and appends to the output_wl
list.