Nekoso
Nekoso

Reputation: 113

How can I slice a list based on the lengths from another list?

I got two lists:

list1 = [4,6,4] 

list2 = [1,1,1,1,0,0,0,0,0,0,1,1,1,1]

Now I want to create a new list, which contains the first four items(because of list1[0] = 4) from list2 as one listelement.

list3 = [(1,1,1,1),(0,0,0,0,0,0),(1,1,1,1)]

Upvotes: 0

Views: 65

Answers (1)

thefourtheye
thefourtheye

Reputation: 239573

You can slice the list based on the values from the list, like this

list1 = [4, 6, 4]
list2 = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1]

# Create an iterator for the list
it = iter(list2)

from itertools import islice
print([tuple(islice(it, item)) for item in list1])

Output

[(1, 1, 1, 1), (0, 0, 0, 0, 0, 0), (1, 1, 1, 1)]

Upvotes: 5

Related Questions