python - split list into nested lists by values in a loop (iterating values) -
i have list of of lists this:
nestedlist = [[0],[0,1,2,3,4,6,7,8,9],[0,1,2,3,4,6,7,8,9],[1,2,3]]
and have homogeneous (same length) list of elements want use split nestedlist
lengthlist = [[1],[5,4],[5,4],[3]]
i tried:
def split(arr, size): arrs = [] while len(arr) > size: pice = arr[:size] arrs.append(pice) arr = arr[size:] arrs.append(arr) return arrs i,j in zip(nestedlist,lengthlist): k in j: mynewlist.append(split(i,k))
but doesn't work 100% right.
the output gives is:
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]]]
instead of
[[[0], [[0, 1, 2, 3, 4], [6, 7, 8, 9]], [[0, 1, 2, 3], [4, 6, 7, 8,9]], [[1, 2, 3]]]
any appreciated.
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 = [] lens,sub in zip(lengthlist, nestedlist): answer.append([]) top = 0 l in lens: answer[-1].append(sub[top:top+l]) top += l
output:
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]]]
Comments
Post a Comment