我有两个列表:
List1=[2,4,3]
List2=[1,2,1,3,2,1,5,4,1]
需要生成这样的输出:
ResultList=[[1,2],[1,3,2,1],[5,4,1]]
需要帮助!!!
以下内容应能在中工作
list1 = [2,4,3]
list2 = [1,2,1,3,2,1,5,4,1]
offset = 0
data = []
for x in list1:
data.append(list2[offset:offset+x])
offset += x
print(data)
输出
[[1, 2], [1, 3, 2, 1], [5, 4, 1]]
你可以试试这个-
result_list=[]
a = 0
for i in list1:
result_list.append(list2[a:a+i])
a += i
from itertools import islice
lengths = [2, 4, 3]
numbers = iter([1, 2, 1, 3, 2, 1, 5, 4, 1])
lists = [list(islice(numbers, length)) for length in lengths]
print(lists)
输出:
[[1, 2], [1, 3, 2, 1], [5, 4, 1]]
>>>