Python split for lists

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

    I'm not sure wether this is the most "pythonic" way of solving it.

    def split_seq(seq, sep):
        start = 0
        while start < len(seq):
            try:
               stop = start + seq[start:].index(sep)
               yield seq[start:stop]
               start = stop + 1
            except ValueError:
               yield seq[start:]
               break
    
    ll = ["data","more data","","data 2","more data 2","danger","","date3","lll"]
    p = [i for i in split_seq(ll,"")]
    

提交回复
热议问题