Make Python Sublists from a list using a Separator

前端 未结 4 1035
别跟我提以往
别跟我提以往 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 12:42

    Simple solution using plain old for-loop (was beaten to it for the groupby solution, which BTW is better!)

    seq = ['|', u'MOM', u'DAD', '|', u'GRAND', '|', u'MOM', u'MAX', u'JULES', '|']
    
    S=[]
    tmp=[]
    
    for i in seq:
        if i == '|':
            S.append(tmp)
            tmp = []
        else:
            tmp.append(i)
    
    # Remove empty lists
    while True:
        try:
            S.remove([])
        except ValueError:
            break
    
    print S
    

    Gives

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

提交回复
热议问题