如果我有一个列表,比如说
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/