Skip to content
Advertisement

python: split a list of strings based on a condition

I have a list like the following:

my_list =['[] [How, you, today] [] []','[] [the] [weather, nice, though] [] []']

I would like to split the list in a way to get the following output.

output_list = ['[]', '[How, you, today]', '[]', '[]','[]', '[the]',
      '[weather, nice, though]', '[]', '[]']

I have tried the following but do not get the result i am looking for.

[word for line in my_list for word in line.split('')]

Advertisement

Answer

Almost. First of all, the following produces what you want –

[('[' + word) if i else word for line in my_list for i, word in enumerate(line.split(' ['))]

More specifically, it seems you want to split by a space-character, but only if it’s the beginning of a new list of words. Hence splitting with ' ['.
Next up you’ll be missing the opening bracket for each list except the first. So by “manually” adding it on for all except the first (by using an enumeration index), you get the requested output.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement