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.
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.
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.
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.
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']
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With