如何根据另一个列表中的长度对列表进行切片?

Nek*_*oso 0 python list

我有两个清单:

list1 = [4,6,4] 

list2 = [1,1,1,1,0,0,0,0,0,0,1,1,1,1]
Run Code Online (Sandbox Code Playgroud)

现在我想创建一个新列表,其中包含前四个项目(因为list1 [0] = 4)来自list2一个监听器.

list3 = [(1,1,1,1),(0,0,0,0,0,0),(1,1,1,1)]
Run Code Online (Sandbox Code Playgroud)

the*_*eye 5

您可以slice根据列表中的值列出该列表,如下所示

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])
Run Code Online (Sandbox Code Playgroud)

产量

[(1, 1, 1, 1), (0, 0, 0, 0, 0, 0), (1, 1, 1, 1)]
Run Code Online (Sandbox Code Playgroud)