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
CodePudding user response:
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)
CodePudding user response:
its my way.
lst = [1,2,3,4,'-',5,6,7,'-',8,9,10,'-',8,9,10,'-',8,9,10]
l=[]
count = 0
start_point = 0
for item in lst:
if item == '-':
l.append(lst[start_point:count])
start_point = count 1
count = 1
if count == len(lst):
l.append(lst[start_point:count])
print(l)
CodePudding user response:
One option could be working with strings:
lst = [1,2,3,4,'-',5,6,7,'-',8,9,10]
[list(map(int, el.split())) for el in ' '.join(map(str,lst)).split(' - ')]
Steps:
- map every element to string:
map(str,lst)
- join every element with spaces:
' '.join(map(...))
- split on
_-_
:' '.join(...).split(' - ')
- for every extracted string:
for el in ...
- split on space:
el.split()
- remap elements to int:
map(int, el.split())
- cast to list:
list(...)