Make Python Sublists from a list using a Separator

前端 未结 4 1013
别跟我提以往
别跟我提以往 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:39
    >>> [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']]
    
    0 讨论(0)
  • 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']]
    
    0 讨论(0)
  • 2020-11-29 12:58
    >>> reduce(
            lambda acc,x: acc+[[]] if x=='|' else acc[:-1]+[acc[-1]+[x]], 
            myList,
            [[]]
        )
    [[], ['MOM', 'DAD'], ['GRAND'], ['MOM', 'MAX', 'JULES'], []]
    

    Of course you'd want to use itertools.groupby, though you may wish to note that my approach "correctly" puts empty lists on the ends. =)

    0 讨论(0)
  • 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']]
    
    0 讨论(0)
提交回复
热议问题