Kallol
Kallol

Reputation: 2189

convert list to list of list and take the length of nested list from another list in python

I have a list like this:

l1=[1,2,3,4,5,7,8,9,23,32,33] 
l2=[5,3,1,2]

I want the final list be look like

l3=[[1,2,3,4,5],[7,8,9],[23],[32,33]]

The length of each nested list will come form l2,

How to do it in efficient way using python.

Upvotes: 0

Views: 124

Answers (4)

Reut Sharabani
Reut Sharabani

Reputation: 31339

You can use itertools:

from itertools import repeat, islice
# itertools works with iterators, so we'll make one
itl1 = iter(l1)

And now if you want a lazy result:

lazy = map(islice, repeat(itl1), l2)

If you want a realized result:

realized = list(map(list, lazy))

The point is that islice depletes the iterator itl1 by the amounts stated in l2 in every step of the map.

Upvotes: 1

jpp
jpp

Reputation: 164673

Here's a solution using itertools.accumulate and pairwise, the latter a recipe available in the itertools docs or available in 3rd party more_itertools.pairwise:

from itertools import accumulate
from more_itertools import pairwise

L1 = [1,2,3,4,5,7,8,9,23,32,33] 
L2 = [5,3,1,2]

L3 = [L1[i: j] for i, j in pairwise(accumulate([0] + L2))]

[[1, 2, 3, 4, 5], [7, 8, 9], [23], [32, 33]]

Upvotes: 0

Chris_Rands
Chris_Rands

Reputation: 41168

You could create an iterator and then create the nested lists:

>>> from itertools import islice
>>> l1=[1,2,3,4,5,7,8,9,23,32,33] 
>>> l2=[5,3,1,2]
>>> it = iter(l1)
>>> [list(islice(it, n)) for n in l2]
[[1, 2, 3, 4, 5], [7, 8, 9], [23], [32, 33]]

Upvotes: 4

Netwave
Netwave

Reputation: 42708

Use a comprehension:

>>> l3 = [[l1.pop(0) for _ in range(x)] for x in l2]
>>> l3
[[1, 2, 3, 4, 5], [7, 8, 9], [23], [32, 33]]

If you dont want to modify l1, use an iterator:

>>> l1=[1,2,3,4,5,7,8,9,23,32,33] 
>>> it = iter(l1)
>>> l3 = [[next(it) for _ in range(x)] for x in l2]
>>> l3
[[1, 2, 3, 4, 5], [7, 8, 9], [23], [32, 33]]

Upvotes: 0

Related Questions