如果我们在python中有一个list,strings并且想要基于一些特殊的条件创建子列表,string我们应该怎么做?
list
strings
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"]]
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']]