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...
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)
[['a'], ['b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i']]
[[l1.pop(0) for x in range(i)] for i in l2]
Output
[['a'], ['b', 'c', 'd'], ['e', 'f'], ['g', 'h', 'i']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With