Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Python Sublists from a list using a Separator

I have for example the following list:

['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|']

and want it to be split by the "|" so the result would look like:

[[u'MOM', u'DAD'],[ u'GRAND'], [u'MOM', u'MAX', u'JULES']]

How can I do this? I only find examples of sublists on the net which need a length of the elements

like image 390
W0bble Avatar asked May 28 '11 20:05

W0bble


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 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.

Can you split an item in a list Python?

To split the elements of a list in Python: Use a list comprehension to iterate over the list. On each iteration, call the split() method to split each string. Return the part of each string you want to keep.


2 Answers

>>> [list(x[1]) for x in itertools.groupby(['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|'], lambda x: x=='|') if not x[0]]
[[u'MOM', u'DAD'], [u'GRAND'], [u'MOM', u'MAX', u'JULES']]
like image 86
Ignacio Vazquez-Abrams Avatar answered Nov 07 '22 14:11

Ignacio Vazquez-Abrams


itertools.groupby() does this very nicely...

>>> import itertools
>>> l = ['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|']
>>> key = lambda sep: sep == '|'
>>> [list(group) for is_key, group in itertools.groupby(l, key) if not is_key]
[[u'MOM', u'DAD'], [u'GRAND'], [u'MOM', u'MAX', u'JULES']]
like image 28
Johnsyweb Avatar answered Nov 07 '22 15:11

Johnsyweb