CodeMonkey
CodeMonkey

Reputation: 1

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

If I have a list of numbers, how can I create a list of lists, where the lenght of each element is predefined in another list of numbers?

Example:

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]]

Is there a generic way to do this assuming that sum(lengths) = len(list) always holds?

Upvotes: 0

Views: 68

Answers (1)

Shubham Shaswat
Shubham Shaswat

Reputation: 1310

Try this:

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

Output

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

Upvotes: 1

Related Questions