Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining elements of a list if those elements are in between two whitespaces

Tags:

I have an input like this:

['assembly', '', 'py', 'tho', 'n', '', 'ja', 'va', '', 'rub', 'y', '', 'java', 'script', '', 'c++'] 

I want to join elements between '' to have an output like this:

['assembly', 'python', 'java', 'ruby', 'javascript', 'c++'] 

I tried using join and list slicing like this:

a=['assembly', '', 'py', 'tho', 'n', '', 'ja', 'va', '', 'rub', 'y', '', 'java', 'script', '', 'c++'] a[2:5] = [''.join(a[ 2: 5])] a=['assembly', '', 'python', '', 'ja', 'va', '', 'rub', 'y', '', 'java', 'script', '', 'c++'] 

This works to some extent but I don't know how to iterate this instruction for the entire list.

like image 369
mewtire Avatar asked Nov 11 '19 11:11

mewtire


2 Answers

Using itertools.groupby:

from itertools import groupby  l = ['assembly', '', 'py', 'tho', 'n', '', 'ja', 'va', '', 'rub', 'y', '', 'java', 'script', '', 'c++'] new_l = [''.join(g) for k, g in groupby(l, key = bool) if k] 

Output:

['assembly', 'python', 'java', 'ruby', 'javascript', 'c++'] 
like image 138
Chris Avatar answered Sep 27 '22 19:09

Chris


This is awful and hacky, but

lambda b:lambda l:''.join(i or b for i in l).split(b) 

can take any string you can guarantee is not contained in the concatenation of the list, and return a function doing what you want. Of course, you probably want to only use this once or twice for your specific situation, so, if you can guarantee that no element of the list contains a space, it might look more like:

a = ['assembly', '', 'py', 'tho', 'n', '', 'ja', 'va', '', 'rub', 'y', '', 'java', 'script', '', 'c++'] a = ''.join(i or ' ' for i in a).split(' ') 
like image 26
Unrelated String Avatar answered Sep 27 '22 19:09

Unrelated String