首页 文章

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

提问于
浏览
0

我有两个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 回答

  • 3

    在数据上创建一个迭代器,然后为它所需的每个范围调用 next

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

    有很多方法可以做到这一点 . 一种方法是使用 itertools.accumulate() 创建切片索引列表

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

    这给出了以下结果:

    [[123, 452],
     [342, 533, 222, 402, 124],
     [125, 263, 254, 44, 987, 78, 655, 741, 165, 597, 26, 15, 799, 100],
     [154, 122, 563]]
    

相关问题