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

Time:08-24

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?

CodePudding user response:

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']]

CodePudding user response:

Something like this:

>>> a = ["a", " ", "b", "i", "g", " ", "d", "o", "g", " ", "b", "i", "t", " ", "m", "e"]
>>> ''.join(a)
'a big dog bit me'
>>> [[word] for word in ''.join(a).split()]
[['a'], ['big'], ['dog'], ['bit'], ['me']]

CodePudding user response:

Try this in one line:

[[i] for i in "".join(a).split()]

CodePudding user response:

Another possible solution:

a = ["a", " ", "b","i","g"," ","d","o", "g"," ","b","i","t"," ","m","e"]
[*map(lambda x: [x], ''.join(a).split())]

#> [['a'], ['big'], ['dog'], ['bit'], ['me']]
  • Related