加入列表中两个元素之间的列表元素
我有一个列表,我有两个列表元素开始:
和结束:
。在这两个之间,我想加入start
元素的不确定元素。 另外,结束:
可以具有不同的名称,但它总是以结束:
开始。这是我的列表
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])))])
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])))])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
获取
开始的索引:
和结束:
。然后,您可以加入它们并使用切片分配将列表的该部分替换为结果。请注意,仅当只有一个
start:/end:
配对时,这才有效。Get the indexes of
start:
andend:
. Then you can join them and use slice assignment to replace that part of the list with the result.Note that this only works if there's just one
start:/end:
pair in the list.您可以使用经典循环:
输出:
You can use a classical loop:
output: