I have a list that I want to split into multiple sublists
acq=['A1', 'A2', 'D', 'A3', 'A4', 'A5', 'D', 'A6'] ll=[] for k,v in enumerate(acq): if v == 'D': continue # continue here ll.append(v) print(ll)
Above solution give gives an expanded appended list, which is not what I am looking for. My desired solution is:
['A1', 'A2'] ['A3', 'A4', 'A5'] ['A6']
Advertisement
Answer
Try itertools.groupby
:
from itertools import groupby acq = ["A1", "A2", "D", "A3", "A4", "A5", "D", "A6"] for v, g in groupby(acq, lambda v: v == "D"): if not v: print(list(g))
Prints:
['A1', 'A2'] ['A3', 'A4', 'A5'] ['A6']