如何将Python列表拆分或分解为不等的块,具有指定的块大小

时间:2017-12-04 19:16:23

标签: python python-3.x

我有两个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个元素,依此类推。

我该怎么做?

3 个答案:

答案 0 :(得分:4)

在数据上创建一个迭代器,然后为它所需的每个范围调用<?php include_once ("../wp-load.php"); $post_id = 4376; $image_url = "https://www.sepatuonline.co.id/wp-content/uploads/raindoz/RSR-006.jpg"; update_images($post_id, $image_url); function update_images($post_id, $image_url) { $image_name = 'wp-header-logo.png'; $upload_dir = wp_upload_dir(); $image_data = wp_remote_get($image_url); $image_data = $image_data['body']; $image_data = json_decode($image_data, true); $unique_file_name = wp_unique_filename( $upload_dir['path'], $image_name ); $filename = basename( $unique_file_name ); if( wp_mkdir_p( $upload_dir['path'] ) ) { $file = $upload_dir['path'] . '/' . $filename; } else { $file = $upload_dir['basedir'] . '/' . $filename; } file_put_contents( $file, $image_data ); $wp_filetype = wp_check_filetype( $filename, null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name( $filename ), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $file, $post_id ); require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); wp_update_attachment_metadata( $attach_id, $attach_data ); set_post_thumbnail( $post_id, $attach_id ); }

next

答案 1 :(得分:1)

这里是一个没有迭代器的衬里:

>>> 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]
>>> [list1[sum(list2[:i]):sum(list2[:i])+n] for i,n in enumerate(list2)]
[[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 :(得分: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]]