Python split for lists

前端 未结 6 1314
眼角桃花
眼角桃花 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:24

    reduce comes to mind:

    def split(iterable, where):
        def splitter(acc, item, where=where):
            if item == where:
                acc.append([])
            else:
                acc[-1].append(item)
            return acc
        return reduce(splitter, iterable, [[]])
    
    
    data = ["data","more data","","data 2","more data 2","danger","","date3","lll"]
    print split(data, '')
    

    Result:

    [['data', 'more data'], ['data 2', 'more data 2', 'danger'], ['date3', 'lll']]
    

提交回复
热议问题