Make Python Sublists from a list using a Separator

前端 未结 4 1029
别跟我提以往
别跟我提以往 2020-11-29 12:15

I have for example the following list:

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

and wan

4条回答
  •  醉梦人生
    2020-11-29 13:00

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

提交回复
热议问题