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

Popular posts from this blog

php - Why I am getting the Error "Commands out of sync; you can't run this command now" -

linux - Does gcc have any options to add version info in ELF binary file? -

java - Are there any classes that implement javax.persistence.Parameter<T>? -