Python joining list elements in a tricky way -


so, have list

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

and, want join them in way such as:

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

i tried lots of methods nothing seemed work. suggestions?

you can use itertools.groupby , list comprehension. group ''s , non '' , join items latter using str.join. ternary operator in rear of comprehension uses group key decide each group:

from itertools import groupby  l = ['abc','retro','','','images','cool','','end']  r = [j k, g in groupby(l, lambda x: x=='')                            j in (g if k else (' '.join(g),))] print(r) # ['abc retro', '', '', 'images cool', '', 'end'] 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -