Does Python come with a function to split a list using a delimiter? -
having list contains strings, want split list @ each point contains empty string (''), e.g.
['this', 'is', '', 'an', 'example'] should become
[['this', 'is'], ['an', 'example']] i wrote generator this:
def split(it, delimiter): = iter(it) buffer = [] while true: element = next(it) if element != delimiter: buffer.append(element) elif buffer: yield buffer buffer = [] since looks pretty general, wondering if missed similar function or related pattern in itertools or somewhere else...?
>>> itertools import groupby >>> words = ['this', 'is', '', 'an', 'example'] >>> [list(g) k, g in groupby(words, ''.__ne__) if k] [['this', 'is'], ['an', 'example']] >>> [list(g) k, g in groupby(words, 'is'.__ne__) if k] [['this'], ['', 'an', 'example']]
Comments
Post a Comment