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

Leo*_*ead 14 python loops list sublist

如果我有一个清单,请说

lst = ['hello', 'foo', 'test', 'world', 'bar', 'idk']
Run Code Online (Sandbox Code Playgroud)

我想将它拆分为一个子列表,'foo'并将其'bar'作为开始和结束关键字,以便我得到

lst = ['hello', ['foo', 'test', 'world', 'bar'], 'idk']
Run Code Online (Sandbox Code Playgroud)

我目前这样做的方式如下.

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
Run Code Online (Sandbox Code Playgroud)

这看起来有点混乱,但它对于嵌套的开始/结束关键字非常有效,因此子列表可以在子列表中形成,但它不适用于多个开始/结束关键字不在彼此内部.嵌套并不重要,所以任何帮助都将受到赞赏.

Mar*_*nen 9

使用切片的一种方法:

>>> lst = ['hello', 'foo', 'test', 'world', 'bar', 'idk']
>>> a=lst.index('foo')
>>> b=lst.index('bar')+1
>>> lst[a:b] = [lst[a:b]]
>>> lst
['hello', ['foo', 'test', 'world', 'bar'], 'idk']
Run Code Online (Sandbox Code Playgroud)

  • @AntonvBR OP的例子不起作用,也没有显示他的意思.请添加您自己的答案,不要编辑我的. (2认同)

Ant*_*vBR 8

多个开始,结束(基于Mark Tolonen的回答)

lst = ['hello', 'foo', 'test', 'world', 'bar', 'idk','am']
t = [('foo','test'),('world','idk')]

def sublists(lst, t):
    for start,end in t:
        a=lst.index(start)
        b=lst.index(end)+1
        lst[a:b] = [lst[a:b]]
    return lst

print(sublists(lst,t)) 
Run Code Online (Sandbox Code Playgroud)

返回:

 ['hello', ['foo', 'test'], ['world', 'bar', 'idk'], 'am']
Run Code Online (Sandbox Code Playgroud)

  • 我不知道这在Op案例中是否重要,但如果它们不止一次出现就会失败:`['A','foo','test','bar','B','foo',' test2','bar']`应该变成'['A',['foo','test','bar'],'B',['foo','test2','bar']]`和不是'['A',['foo','test','bar'],'B','foo','test2','bar']`.还有什么呢?''''','foo ','bar','bar']`.它应该分组为"['foo','bar']`(作为你的代码)或`['foo','bar','bar']`? (3认同)

Eri*_*nil 1

一种创造性的方法是将列表转储到JSON字符串,在需要的地方添加[],然后将 JSON 字符串解析回 Python 嵌套列表:

import json
lst = ['hello', 'foo', 'test', 'world', 'bar', 'idk']
start_keywords = ['world', 'foo', 'test']
end_keywords = ['bar', 'idk', 'foo']
dump = json.dumps(lst)

for k in start_keywords:
    dump = dump.replace(f'"{k}"', f'["{k}"')

for k in end_keywords:
    dump = dump.replace(f'"{k}"', f'"{k}"]')

json.loads(dump)
# ['hello', ['foo'], ['test', ['world', 'bar'], 'idk']]
json.loads(dump)[2][1][0]
# 'world'
Run Code Online (Sandbox Code Playgroud)

优点是它很容易理解,它适用于任意嵌套列表,并且它可以检测结构是否不正确。不过,您需要确保您的单词不包含"