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.
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++']
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(' ')
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