Python split for lists

前端 未结 6 1313
眼角桃花
眼角桃花 2020-11-28 12:43

If we have a list of strings in python and want to create sublists based on some special string how should we do?

For instance

6条回答
  •  爱一瞬间的悲伤
    2020-11-28 13:05

    itertools.groupby is one approach (as it often is):

    >>> l = ["data","more data","","data 2","more data 2","danger","","date3","lll"]
    >>> from itertools import groupby
    >>> groupby(l, lambda x: x == "")
    
    >>> [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']]
    

    We can even cheat a little because of this particular case:

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

提交回复
热议问题