Python split for lists

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

    Heres one idea. :)

    def spec_split(seq,sep):
        # Ideally this separator will never be in your list
        odd_sep = "!@#$%^&*()"
    
        # Join all the items with the odd separator and split
        # anywhere the odd separator + separator + odd seperator meet
        # This makes a list of items broken by the separator
        jumble = odd_sep.join(seq).split(odd_sep+sep+odd_sep)
    
        # split the remaining items broken by odd separators into sublists
        return [item.split(odd_sep) for item in jumble] 
    

提交回复
热议问题