如何使用指定的块大小将 Python 列表拆分或分解为不相等的块 [英] How to Split or break a Python list into Unequal chunks, with specified chunk sizes

查看:35
本文介绍了如何使用指定的块大小将 Python 列表拆分或分解为不相等的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 Python 数字列表.

list1 = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,156,322]list2 = [2,5,14,3] ##这些数字指定了所需的块大小

我想通过根据 list2 中的大小数字拆分 list1 来创建 list1 的子集或子列表.结果,我想要这个:

a_list = [123,452] ##对应list2中的第一个元素(2);从 list1 中获取前两个数字b_list = [342,533,222,402,124] ##对应list2中的第二个元素(5);从 list1 中获取接下来的 5 个数字c_list = [125,263,254,44,987,78,655,741,165,597,26,15,799,100] ##next 14 个数字来自 list1d_list = [154,122,563] ##list1 中的下 3 个数字

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

我该怎么做?

解决方案

在数据上创建一个迭代器,然后针对您需要的每个范围调用next:

<预><代码>>>>数据 = [123,452,342,533,222,402,124,125,263,254,44,987,78,655,741,165,597,26,15,799,100,154,122,563]>>>尺寸 = [2, 5, 14, 3]>>>it = iter(数据)>>>[[next(it) for _ in range(size)] for size in size][[123, 452],[342, 533, 222, 402, 124],[125, 263, 254, 44, 987, 78, 655, 741, 165, 597, 26, 15, 799, 100],[154, 122, 563]]

I have two Python lists of numbers.

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  

I would like to create subsets or sub-lists of list1 by splitting list1 according to the size numbers in list2. As a result, I would like to have this:

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  

Essentially, each chunk should follow list2. This means, the first chunk should have the first 2 elements from list1, the second chunk should have the next 5 elements, and so on.

How can I do this?

解决方案

Create an iterator over the data, and then call next on it for each range you need:

>>> 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]]

这篇关于如何使用指定的块大小将 Python 列表拆分或分解为不相等的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆