Search code examples
pythonpython-3.xlistsplitconcatenation

How to split a python list based on specific characters like spaces and forward slashes?


Suppose that you have the python list:

a = ["a", " ", "b", "i", "g", " ", "d", "o", "g", " ", "b", "i", "t", " ", "m", "e"]

Is there a way to split this list such that you get:

a = [["a"],["big"],["dog"],["bit"],["me"]]

or similar?


Solution

  • Using itertools.groupby:

    a = ['a', ' ', 'b', 'i', 'g', ' ', 'd', 'o', 'g', ' ',
         'b', 'i', 't', ' ', 'm', 'e']
    
    from itertools import groupby
    
    out = [[''.join(g)] for k, g in groupby(a, lambda x: x!=' ') if k]
    

    output: [['a'], ['big'], ['dog'], ['bit'], ['me']]