'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
Solution 1:[1]
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)
Solution 2:[2]
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]]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kenntnisse |
| Solution 2 | inquirer |
