[英]join list elements between two elements in a list
我有一個列表,我有兩個列表元素start:
和end:
。 在這兩者之間,我想加入到start
元素的元素數量未定義。 此外, end:
可以有不同的名稱,但它總是以end:
開頭。 這是我的清單
sth_list = ['name: michael', 'age:56', 'start:','','something','is','happening','end:', 'anything could be here:', 'some other things:', 'more things:']
我想得到這個
['name: michael', 'age:56', 'start: something is happening', 'end:', 'anything could be here:', 'some other things:', 'more things:']
到目前為止我所擁有的是這個。 但它只給了我開始和結束之間的連接元素,但我想要上面的完整列表。
''.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])))])
您可以使用經典循環:
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
輸出:
['name: michael',
'age:56',
'start: something is happening',
'end:',
'anything could be here:',
'some other things:',
'more things:']
獲取start:
和end:
的索引。 然后您可以加入它們並使用切片分配將列表的那部分替換為結果。
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])]
請注意,這僅適用於列表中只有一個start:/end:
對的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.