I have a list like the following:

lst = ['a', 'a', 'a', 'start', 'b', 'end', 'a', 'a','a','start','b','b','b','end','a','a','a','a','start','b','b','end']

and my desired result is to split the list into sublists like this:

[['a', 'a', 'a'], ['start', 'b', 'end'], ['a', 'a','a'],['start','b','b','b','end'],['a','a','a','a'],['start','b','b','end']]

so start and end are keywords, is there anyway you can use .split() by using particular keywords/if it matches?

So far I have made a function which finds the indices of 'start' i.e. starting_ind = [3, 9, 18] and ending_ind = [5, 13, 21] however if I do

temp=[]
for i in range(len(starting_ind)):
       x = lst[starting_ind[i]: ending_ind[i]]
       temp += x
print(temp)     

the result is incorrect.

推荐答案

This solution doesn't require you to calculate indices beforehand:

lst = ['a', 'a', 'a', 'start', 'b', 'end', 'a', 'a', 'a', 'start', 'b', 'b',
       'b', 'end', 'a', 'a', 'a', 'a', 'start', 'b', 'b', 'end', 'a', 'a', 'a']
result = []
sublist = []

for el in range(len(lst)):
  if lst[el] == 'start':
    result.append(sublist.copy())
    sublist.clear()
    sublist.append(lst[el])
  else:
    sublist.append(lst[el])
    if lst[el] == 'end':
      result.append(sublist.copy())
      sublist.clear()
    if el == len(lst) - 1:
      result.append(sublist)
print(result)

The result is:

[['a', 'a', 'a'], ['start', 'b', 'end'], ['a', 'a', 'a'], ['start', 'b', 'b', 'b', 'end'], ['a', 'a', 'a', 'a'], ['start', 'b', 'b', 'end'], ['a', 'a', 'a']]

Python相关问答推荐

通过优化空间在Python中的饼图中添加标签

如何在具有重复数据的pandas中对groupby进行总和,同时保留其他列

Django mysql图标不适用于小 case

Gekko:Spring-Mass系统的参数识别

_repr_html_实现自定义__getattr_时未显示

切片包括面具的第一个实例在内的眼镜的最佳方法是什么?

mypy无法推断类型参数.List和Iterable的区别

重置PD帧中的值

循环浏览每个客户记录,以获取他们来自的第一个/最后一个渠道

30个非DATETIME天内的累计金额

在用于Python的Bokeh包中设置按钮的样式

BeautifulSoup-Screper有时运行得很好,很健壮--但有时它失败了::可能这里需要一些更多的异常处理?

Js的查询结果可以在PC Chrome上显示,但不能在Android Chrome、OPERA和EDGE上显示,而两者都可以在Firefox上运行

如何为需要初始化的具体类实现依赖反转和接口分离?

Polars表达式无法访问中间列创建表达式

将数字数组添加到Pandas DataFrame的单元格依赖于初始化

如何在PYTHON中向单元测试S Side_Effect发送额外参数?

如何在表单中添加管理员风格的输入(PDF)

如何删除剪裁圆的对角线的外部部分

在Django REST框架中定义的URL获得404分