使用分隔符从列表中创建 Python 子列表 [英] Make Python Sublists from a list using a Separator

查看:51
本文介绍了使用分隔符从列表中创建 Python 子列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有以下列表:

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

推荐答案

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

这篇关于使用分隔符从列表中创建 Python 子列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆