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.
Say I have a list containing lists of words:
words = [
['this','that!','riff','raff'],
['hip','hop!','flip!','flop'],
['humpty','dumpty!','professor!','grumpy!']
]
How do I combine only those elements that contain an !
?
For example, the output would look like this:
[['this', 'that!', 'riff', 'raff'],
['hip', 'hop!, flip!', 'flop'], # 1,2 are now combined
['humpty', 'dumpty!, professor!, grumpy!']] # 1,2,3 are now combined
I tried this:
for word in words:
word = ', '.join(i for i in word if re.search('!',str(i)))
print word
but got:
that!
hop!, flip!
dumpty!, professor!, grumpy!
Thank you.
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!']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With