Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

splitting a python list into sublists

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']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading