Make Python Sublists from a list using a Separator

百般思念 提交于 2019-12-17 06:54:05

问题


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


回答1:


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



回答2:


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



回答3:


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



回答4:


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



来源:https://stackoverflow.com/questions/6164313/make-python-sublists-from-a-list-using-a-separator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!