一尘不染

Python拆分列表

python

如果我们在python中有一个liststrings并且想要基于一些特殊的条件创建子列表,string我们应该怎么做?

例如:

l = ["data","more data","","data 2","more data 2","danger","","date3","lll"]
p = split_special(l,"")

会产生:

p = [["data","more data"],["data 2","more data 2","danger"],["date3","lll"]]

阅读 191

收藏
2020-12-20

共1个答案

一尘不染

itertools.groupby是一种方法(通常是这样):

>>> l = ["data","more data","","data 2","more data 2","danger","","date3","lll"]
>>> from itertools import groupby
>>> groupby(l, lambda x: x == "")
<itertools.groupby object at 0x9ce06bc>
>>> [list(group) for k, group in groupby(l, lambda x: x == "") if not k]
[['data', 'more data'], ['data 2', 'more data 2', 'danger'], ['date3', 'lll']]

由于这种特殊情况,我们甚至可以作弊:

>>> [list(group) for k, group in groupby(l, bool) if k]
[['data', 'more data'], ['data 2', 'more data 2', 'danger'], ['date3', 'lll']]
2020-12-20