Search code examples
pythonsplitsublist

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


Solution

  • >>> [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']]