Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine elements of lists if some condition

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.

like image 289
tmthyjames Avatar asked Dec 11 '14 18:12

tmthyjames


1 Answers

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!']]
like image 188
Ashwini Chaudhary Avatar answered Sep 28 '22 18:09

Ashwini Chaudhary