相关疑难解决方法(0)

如何使用指定的块大小将 Python 列表拆分或分解为不相等的块

我有两个 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  
Run Code Online (Sandbox Code Playgroud)

我想通过根据 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  
Run Code Online (Sandbox Code Playgroud)

本质上,每个块都应该遵循 list2。这意味着,第一个块应该有 list1 中的前 2 个元素,第二个块应该有接下来的 5 个元素,依此类推。 …

python python-3.x

0
推荐指数
1
解决办法
1262
查看次数

标签 统计

python ×1

python-3.x ×1