เมื่อต้องการแยกลิสต์ตามความยาวที่กำหนดในลิสต์อีกอันหนึ่ง สามารถใช้ list comprehension, iter() และ islice() จากโมดูล itertools ได้
ตัวอย่าง
from itertools import islice
my_list = [11, 22, 33, 34, 45, 26, 87, 11]
print("The list is :")
print(my_list)
length_to_split = [2, 5, 3]
print("The split length list is :")
print(length_to_split)
temp = iter(my_list)
my_result = [list(islice(temp, element)) for element in length_to_split]
print("The result is :")
print(my_result)
ผลลัพธ์
The list is : [11, 22, 33, 34, 45, 26, 87, 11] The split length list is : [2, 5, 3] The result is : [[11, 22], [33, 34, 45, 26, 87], [11]]
คำอธิบาย
นำเข้า
isliceจากitertoolsกำหนดลิสต์ข้อมูลและลิสต์ความยาวที่ต้องการแยก
สร้าง iterator จากลิสต์ข้อมูลด้วย
iter()ใช้ list comprehension วนลูปผ่านลิสต์ความยาว ใช้
islice()ตัดข้อมูลตามจำนวนที่กำหนดจาก iterator แล้วแปลงเป็นลิสต์แสดงผลลัพธ์ที่ได้