How to Split or break a Python list into Unequal chunks, with specified chunk sizes
我有两个python数字列表。
1 2 | 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 |
我想通过根据列表2中的大小数字拆分列表1来创建列表1的子集或子列表。因此,我希望:
1 2 3 4 | 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 |
本质上,每个块都应该遵循列表2。这意味着,第一个块应该具有来自列表1的前2个元素,第二个块应该有接下来的5个元素,以此类推。
我该怎么做?
在数据上创建一个迭代器,然后针对所需的每个范围对其调用
1 2 3 4 5 6 7 8 | >>> data = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,154,122,563] >>> sizes = [2, 5, 14, 3] >>> it = iter(data) >>> [[next(it) for _ in range(size)] for size in sizes] [[123, 452], [342, 533, 222, 402, 124], [125, 263, 254, 44, 987, 78, 655, 741, 165, 597, 26, 15, 799, 100], [154, 122, 563]] |
有很多方法可以做到这一点。一种方法是使用
1 2 3 4 5 6 | from itertools import accumulate 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 ind = [0] + list(accumulate(list2)) [list1[ind[i]:ind[i+1]] for i in range(len(ind)-1)] |
结果如下:
1 2 3 4 | [[123, 452], [342, 533, 222, 402, 124], [125, 263, 254, 44, 987, 78, 655, 741, 165, 597, 26, 15, 799, 100], [154, 122, 563]] |