Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a list to sublists with sizes given in another list [duplicate]

Tags:

python

list

I have these lists:

l1 = [a,b,c,d,e,f,g,h,i]
l2 = [1,3,2,3]

How can I split l1 this way?

[[a],[b,c,d],[e,f],[g,h,i]]

-The first element is a list of one element because of the 1 of l2
-The second element is a list of three elements because of the 3 of l2
-The third element is a list of two elements because of the 2 of l2
-The fourth element is a list of three elements because of the 3 of l2

I've tried using a function:

def divide(num, n):
        return [num[i*n : (i+1)*n] for i in range(len(num)//n)]  

x = divide(l2,1)
for i in range(len(l2)):
    z = x[i]
    divide(l1,z)

But it's not working...

like image 252
queenbegop777 Avatar asked Dec 31 '22 00:12

queenbegop777


2 Answers

Code

l1 = ['a','b','c','d','e','f','g','h','i']
l2 = [1,3,2,3]

start = 0
l = []
for i in l2:
    l.append(l1[start: start+i])
    start = start + i
print(l)

Output

[['a'], ['b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i']]
like image 173
han Avatar answered Jan 02 '23 14:01

han


[[l1.pop(0) for x in range(i)] for i in l2]

Output

[['a'], ['b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i']]
like image 22
Chris Avatar answered Jan 02 '23 13:01

Chris