If I were to have a list, say
lst = ['hello', 'foo', 'test', 'world', 'bar', 'idk']
I'd like to split it into a sublist with 'foo' and 'bar' as start and end keywords, so that I would get
lst = ['hello', ['foo', 'test', 'world', 'bar'], 'idk']
The way I am currently doing this is as follows.
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
This looks a bit messy, but it works very well for nested start/end keywords, so sublists can be formed inside of sublists, but it does not work for multiple start/end keywords not being inside eachother. Being nested is not important yet, so any help would be appreciated.
One way using slicing:
>>> 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']
multiple start,ends (based on Mark Tolonen's answer)
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))
Returns:
['hello', ['foo', 'test'], ['world', 'bar', 'idk'], 'am']
Using slicing, without support for nested lists:
>>> lst = ['hello', 'foo', 'test', 'world', 'bar', 'idk']
>>> start_idx = lst.index('foo')
>>> end_idx = lst.index('bar')
>>> lst[:start_idx] + [lst[start_idx:end_idx+1]] + lst[end_idx+1:]
['hello', ['foo', 'test', 'world', 'bar'], 'idk']