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

How do i split a list and and turn it into two dimensional list?

I have a list: lst = [1,2,3,4,'-',5,6,7,'-',8,9,10]
that needs to be split when the ‘-‘ character is encountered. and turned into a two dimensional list like so:
[[1,2,3,4],[5,6,7],[8,9,10]]
I have this so far and all it does is take the ‘-‘ character out:

l=[]
for item in lst:
   if item != '-':
      l.append(item)

return l

I’m learning how to code so I would appreciate the help

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 :

new_list = [] #final result
l=[] #current nested list to add
for item in lst:
    if item != '-':
        l.append(item) # not a '-', so add to current nested list
    else: #if item is not not '-', then must be '-'
        new_list.append(l) # nested list is complete, add to new_list
        l = [] # reset nested list
print(new_list)
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