python - Split a list into chunks determined by a separator -
i have list (python):
[item1],[item2],[item3],[/],[item4],[item5],[item6],[/]...and on.
i want separate these chunks , elements go each chunk elements before separator "/".
so chunks like:
chunk1:[item1],[item2],[item3] chunk2:[item4],[item5],[item6]
i've tried , tried, nothing efficient came mind. tried looping through , and if element[x] == '/' positions. it's dirty , doesn't work.
any appreciated.
the usual approach collecting contiguous chunks use itertools.groupby
, example:
>>> itertools import groupby >>> blist = ['item1', 'item2', 'item3', '/', 'item4', 'item5', 'item6', '/'] >>> chunks = (list(g) k,g in groupby(blist, key=lambda x: x != '/') if k) >>> chunk in chunks: ... print(chunk) ... ['item1', 'item2', 'item3'] ['item4', 'item5', 'item6']
(your representation of list [item1],[item2],[item3],[/],
makes each of elements in list list, in case same approach work, need compare against ['/']
or whatever separator is.)
Comments
Post a Comment