Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python joining list elements in a tricky way

So, I have this list

l = ['abc', 'retro', '', '', 'images', 'cool', '', 'end']

and, I want to join them in a way such as:

l = ['abc retro', '', '', 'images cool', '', 'end']

I tried lots of methods but nothing seemed to work. Any suggestions?

like image 799
Karmesh Maheshwari Avatar asked Apr 06 '17 10:04

Karmesh Maheshwari


1 Answers

You can use itertools.groupby and a list comprehension. Group into ''s and non '' and join items from the latter using str.join. The ternary operator in the rear of the comprehension uses the group key to decide what to do for each group:

from itertools import groupby

l = ['abc','retro','','','images','cool','','end']

r = [j for k, g in groupby(l, lambda x: x=='') 
                          for j in (g if k else (' '.join(g),))]
print(r)
# ['abc retro', '', '', 'images cool', '', 'end']
like image 128
Moses Koledoye Avatar answered Sep 29 '22 05:09

Moses Koledoye