我有一个像这样的列表列表:
nestedList = [[0],[0,1,2,3,4,6,7,8,9],[0,1,2,3,4,6,7,8,9],[1,2,3]]
我有另一个同质(相同长度)的元素列表,我想用它来分割nestedList
lengthList = [[1],[5,4],[5,4],[3]]
我试过了:
def split(arr, size):
arrs = []
while len(arr) > size:
pice = arr[:size]
arrs.append(pice)
arr = arr[size:]
arrs.append(arr)
return arrs
for i,j in zip(nestedList,lengthList):
for k in j:
myNewList.append(split(i,k))
但它没有100%正确地工作。
它给出的输出是:
myNewList = [[[0]], [[0, 1, 2, 3, 4], [6, 7, 8, 9]], [[0, 1, 2, 3], [4, 6, 7, 8], [9]], [[0, 1, 2, 3, 4], [6, 7, 8, 9]], [[0, 1, 2, 3], [4, 6, 7, 8], [9]], [[1, 2, 3]]]
而不是
[[[0], [[0, 1, 2, 3, 4], [6, 7, 8, 9]], [[0, 1, 2, 3], [4, 6, 7, 8,9]], [[1, 2, 3]]]
任何帮助都将不胜感激。
答案 0 :(得分:2)
nestedList = [[0],[0,1,2,3,4,6,7,8,9],[0,1,2,3,4,6,7,8,9],[1,2,3]]
lengthList = [[1],[5,4],[5,4],[3]]
answer = []
for lens,sub in zip(lengthList, nestedList):
answer.append([])
top = 0
for l in lens:
answer[-1].append(sub[top:top+l])
top += l
输出:
In [2]: answer
Out[2]:
[[[0]],
[[0, 1, 2, 3, 4], [6, 7, 8, 9]],
[[0, 1, 2, 3, 4], [6, 7, 8, 9]],
[[1, 2, 3]]]
答案 1 :(得分:0)
这是您需要的解决方案
# stackoverflow.com
# Python
# split list into nested lists by values in a loop (iterating values)
nestedList = [[0],[0,1,2,3,4,6,7,8,9],[0,1,2,3,4,6,7,8,9],[1,2,3]]
lengthList = [[1],[5,4],[5,4],[3]]
def toOneList (array):
oneList = []
if len(array) > 0:
for subList in array:
for x in subList:
oneList.append(x)
return oneList
def grouping(array, size):
newList = []
i = 0
for j in size:
newList.append(array[i:i+j])
i = i + j
return newList
nestedList = toOneList(nestedList)
lengthList = toOneList(lengthList)
print(grouping(nestedList, lengthList))
答案 2 :(得分:0)
试试这段代码
# stackoverflow.com
# Python
# split list into nested lists by values in a loop (iterating values)
nestedList = [[0],[0,1,2,3,4,6,7,8,9],[0,1,2,3,4,6,7,8,9],[1,2,3]]
lengthList = [[1],[5,4],[5,4],[3]]
def toOneList (array):
oneList = []
if len(array) > 0:
for subList in array:
for x in subList:
oneList.append(x)
return oneList
def grouping(array, size):
newList = []
i = 0
for j in size:
newList.append(array[i:i+j])
i = i + j
return newList
nestedList = toOneList(nestedList)
lengthList = toOneList(lengthList)
print(grouping(nestedList, lengthList))