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

Question:

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

Asked By: abeishere

||

Answers:

You can build a new list that will contain only the numeric values:

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)
Answered By: kenntnisse
import numpy as np
import more_itertools as mit

lst = np.array([1, 2, 3, 4, '-', 5, 6, 7, '-', 8, 9, 10])
aaa = list(mit.split_at(lst, pred=lambda x: set(x) & {'-'}))
bbb = [list(map(int, i)) for i in aaa]

Output bbb

[[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
Answered By: inquirer