Home > front end >  join list elements between two elements in a list
join list elements between two elements in a list

Time:05-24

I have a list and I have the two list elements start:and end:. Between these two there is an undefined number of elements that I would like to join to the start element. Also, end: can have different names but it always starts with end:. This is my list

sth_list = ['name: michael', 'age:56', 'start:','','something','is','happening','end:', 'anything could be here:', 'some other things:', 'more things:'] 

and I would like to get this

 ['name: michael', 'age:56', 'start: something is happening', 'end:', 'anything could be here:', 'some other things:', 'more things:']

what I have so far is this. But it only gives me the joined elements between start and end but I would like to have the full list as above.

 ''.join([element for n, element in enumerate(sth_list) if ((n>sth_list.index("start:")) & (n<sth_list.index([e for e in sth_list if e.startswith('end')][0])))])

CodePudding user response:

Get the indexes of start: and end:. Then you can join them and use slice assignment to replace that part of the list with the result.

start = sth_list.index('start:')
end = min(i for i, s in enumerate(sth_list) if s.startswith('end:'))
sth_list[start:end] = [' '.join(sth_list[start:end])]

Note that this only works if there's just one start:/end: pair in the list.

CodePudding user response:

You can use a classical loop:

import re

out = []
flag = False
for item in sth_list:
    if item.startswith('end:'):
        flag = False
    if flag:
        if item:
            out[-1]  = ' ' item
    else:
        out.append(item)
    if item == 'start:':
        flag = True

output:

['name: michael',
 'age:56',
 'start: something is happening',
 'end:',
 'anything could be here:',
 'some other things:',
 'more things:']
  • Related