Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python splitting list to sublists at given start/end keywords

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.

like image 768
Leo Whitehead Avatar asked Feb 14 '18 09:02

Leo Whitehead


People also ask

How do you divide a list into equal Sublists in Python?

Split List Into Sublists Using the array_split() Function in NumPy. The array_split() method in the NumPy library can also split a large array into multiple small arrays. This function takes the original array and the number of chunks we need to split the array into and returns the split chunks.

How do you split a list into evenly sized chunks?

The easiest way to split list into equal sized chunks is to use a slice operator successively and shifting initial and final position by a fixed number.

How do you break a list of elements in Python?

Method 3: Break a list into chunks of size N in Python using Numpy. Here, we are using a Numpy. array_split, which splits the array into n chunks of equal size.


2 Answers

One way using slicing:

>>> 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']
like image 193
Mark Tolonen Avatar answered Sep 22 '22 09:09

Mark Tolonen


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']
like image 25
Anton vBR Avatar answered Sep 21 '22 09:09

Anton vBR