创建列表列表,其中每个元素的长度在另一个列表中定义

Create list of lists, where the length of each element is defined in another list

如果我有一个数字列表,我该如何创建一个列表列表,其中每个元素的长度都在另一个数字列表中预定义?

示例:

list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
lengths = [6,5,1,3,1] #in ascending order
result = [[1,2,3,4,5,6],[7,8,9,10,11],[12],[13,14,15],[16]]

假设 sum(lengths) = len(list) 始终成立,是否有一种通用的方法可以做到这一点?

试试这个:

s=0
l=[]
for i in lengths:
  l.append(list[s:s+i])
  s+=i

输出

[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11], [12], [13, 14, 15], [16]]