I have a list like the following
list_1 = ['>name', 'aaa', 'bbb', '>name_1', 'ccc', '>name_2', 'ddd', 'eee', 'fff']
I was trying to join the items between the items with the '>" sign. So what I want is:
list_1 = ['>name', 'aaabbb', '>name_1', 'ccc', '>name_2', 'dddeeefff']
How can I do that in python?
Use a generator function; that lets you control when items are 'done' to yield:
def join_unescaped(it):
tojoin = []
for element in it:
if element.startswith('>'):
if tojoin:
yield ''.join(tojoin)
tojoin = []
yield element
else:
tojoin.append(element)
if tojoin:
yield ''.join(tojoin)
To produce a new list then from your input, pass the generator object produced to the list()
function:
result = list(join_unescaped(list_1))
Demo:
>>> list_1 = ['>name', 'aaa', 'bbb', '>name_1', 'ccc', '>name_2', 'ddd', 'eee', 'fff']
>>> def join_unescaped(it):
... tojoin = []
... for element in it:
... if element.startswith('>'):
... if tojoin:
... yield ''.join(tojoin)
... tojoin = []
... yield element
... else:
... tojoin.append(element)
... if tojoin:
... yield ''.join(tojoin)
...
>>> list(join_unescaped(list_1))
['>name', 'aaabbb', '>name_1', 'ccc', '>name_2', 'dddeeefff']
>>> from itertools import groupby
>>> list_1 = ['>name', 'aaa', 'bbb', '>name_1', 'ccc', '>name_2', 'ddd', 'eee', 'fff']
>>> [''.join(v) for k, v in groupby(list_1, key=lambda s: s.startswith('>'))]
['>name', 'aaabbb', '>name_1', 'ccc', '>name_2', 'dddeeefff']
The only case to watch for here is if you have no items between >
signs, which requires a simple fix.
>>> list_1 = ['>name', '>name0', 'aaa', 'bbb', '>name_1', 'ccc', '>name_2', 'ddd', 'eee', 'fff']
>>> [''.join(v) for k,v in groupby(list_1,key=lambda s:s.startswith('>')and s)]
['>name', '>name0', 'aaabbb', '>name_1', 'ccc', '>name_2', 'dddeeefff']
Sub note: just in the extremely unlikely case that you can have duplicate >name
s like ['>name', '>name', 'aaa'....]
just change and s
to and object()
(which is unique) and that handles every possible case
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