shaz shaz - 3 months ago 7
Python Question

Proper way to split Python list into list of lists on matching list item delimeter

list = ['a', 'b', 'c', '', 'd', 'e', 'f', '', 'g','h','i']

def chunk(list, delim):
ct = list.count(delim)
chunks = [[]] * (ct+1)
for iter in range(ct):
idx = list.index(delim)
chunks[iter] = list[:idx]
list = list[idx+1:]
chunks[ct] = list
return chunks

print chunk(list, '')


Produces:

[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]


Which is what I want, but I feel like this is the 'c' way to accomplish this. Is there a more pythonistic construct I should know?

Answer

Here is one way to do it using itertools.groupby

[list(v) for k, v in groupby(l, key=lambda x: x!= '') if k]

Demo:

>>> from itertools import groupby
>>> l = ['a', 'b', 'c', '', 'd', 'e', 'f', '', 'g','h','i']
>>> ch = [list(v) for k, v in groupby(l, key=lambda x: x!= '') if k]
>>> ch
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]