我有两个Python数字列表 .
list1 = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,154,122,563]
list2 = [2,5,14,3] ##these numbers specify desired chunk sizes
我想通过根据list2中的大小数分割list1来创建list1的子集或子列表 . 结果,我想这样:
a_list = [123,452] ##correspond to first element (2) in list2; get the first two numbers from list1
b_list = [342,533,222,402,124] ##correspond to second element (5) in list2; get the next 5 numbers from list1
c_list = [125,263,254,44,987,78,655,741,165,597,26,15,799,100] ##next 14 numbers from list1
d_list = [154,122,563] ##next 3 numbers from list1
基本上,每个块应该遵循list2 . 这意味着,第一个块应该具有list1中的前2个元素,第二个块应该具有接下来的5个元素,依此类推 .
我怎样才能做到这一点?
2 回答
在数据上创建一个迭代器,然后为它所需的每个范围调用
next
:有很多方法可以做到这一点 . 一种方法是使用
itertools.accumulate()
创建切片索引列表这给出了以下结果: