0

I have a list of strings that looks as follows:

example = ['1','4','6','7','9','...','11','14','18','...','21']

Now, I want to turn example into a list of lists of strings based on the divisor string '...'

My desired output is:

output = [['1','4','6','7','9'],['11','14','18'],['21']]

I used the following code, but this seems cumbersome:

output = []
temp_list = []
for sign in example:
    if sign == '...':
        output.append(temp_list)
        temp_list = []
    else:
        temp_list.append(sign)
output.append(temp_list)
Emil
  • 1,531
  • 3
  • 22
  • 47

1 Answers1

2

Try itertools.groupby:

from itertools import groupby

example = ["1", "4", "6", "7", "9", "...", "11", "14", "18", "...", "21"]

out = [list(g) for k, g in groupby(example, lambda v: v != "...") if k]
print(out)

Prints:

[['1', '4', '6', '7', '9'], ['11', '14', '18'], ['21']]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91