我如何拆分列表并将其转换为二维列表?
How do i split a list and and turn it into two dimensional list?
我有一个列表:lst = [1,2,3,4,'-',5,6,7,'-',8,9,10]
遇到'-'字符时需要拆分。并变成这样的二维列表:
[[1,2,3,4],[5,6,7],[8,9,10]]
到目前为止我有这个,它所做的就是去掉“-”字符:
l=[]
for item in lst:
if item != '-':
l.append(item)
return l
我正在学习如何编码,因此非常感谢您的帮助
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)
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]
输出bbb
[[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
我有一个列表:lst = [1,2,3,4,'-',5,6,7,'-',8,9,10]
遇到'-'字符时需要拆分。并变成这样的二维列表:
[[1,2,3,4],[5,6,7],[8,9,10]]
到目前为止我有这个,它所做的就是去掉“-”字符:
l=[]
for item in lst:
if item != '-':
l.append(item)
return l
我正在学习如何编码,因此非常感谢您的帮助
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)
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]
输出bbb
[[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]