Python 将列表拆分为给定开始/结束关键字的子列表

标签 python list loops sublist

如果我有一个列表,比如说

lst = ['hello', 'foo', 'test', 'world', 'bar', 'idk']

我想将它分成一个子列表,以 'foo''bar' 作为开始和结束关键字,这样我就可以得到

lst = ['hello', ['foo', 'test', 'world', 'bar'], 'idk']

我目前的做法如下。

def findLoop(t):   
    inds = [index for index, item in enumerate(t) if item in ["FOO", "BAR"]]
    centre = inds[(len(inds)/2)-1:(len(inds)/2)+1]
    newCentre = t[centre[0]:centre[1]+1]
    return t[:centre[0]] + [newCentre] + t[centre[1]+1:]

def getLoops(t):
    inds = len([index for index, item in enumerate(t) if item in ["FOO", "BAR"]])
    for i in range(inds):
        t = findLoop(t)
    return t

这看起来有点乱,但它对嵌套的开始/结束关键字非常有效,因此可以在子列表内部形成子列表,但它不适用于不在彼此内部的多个开始/结束关键字。嵌套还不重要,因此我们将不胜感激。

最佳答案

一种使用切片的方法:

>>> lst = ['hello', 'foo', 'test', 'world', 'bar', 'idk']
>>> a=lst.index('foo')    # locate start word
>>> b=lst.index('bar')+1  # locate end word
>>> lst[a:b] = [lst[a:b]] # replace list slice with a list of the slice
>>> lst
['hello', ['foo', 'test', 'world', 'bar'], 'idk']

关于Python 将列表拆分为给定开始/结束关键字的子列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48783894/

相关文章:

C# 字符串排序...如何比较非序数但以相同字母开头的字符串将小写放在大写后面?

python - 将列表解析为变量和子列表 - pythonic 方式

python - 有谁知道哪里有序列化数据并在输出中保留其顺序的方法?

python - 如何记录 Python 交互式 shell session 中发生的一切?

python - 在python中打印多个空行

java - 如何删除字符串(句子)中的空格

java - EnumSet 可以按书面顺序返回值吗?

python - 存储和读取大量 3d 数据集的节省空间的方法?

python - 为什么 python 中的列表会这样?

javascript - Nodejs 请求、循环和 promise