Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การแบ่งลิสต์เป็นชิ้นขนาดเท่ากัน (Chunks) ใน Python

วิธีง่ายที่สุดคือใช้ slice operator [start:stop] ซ้ำๆ พร้อมเลื่อนตำแหน่งเริ่มต้นและสิ้นสุดทีละจำนวนคงที่

ตัวอย่าง: แบ่งลิสต์ 12 สมาชิก เป็น 3 ชิ้น ชิ้นละ 4 ตัว

l = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]
chunk_size = 4
chunks = [l[i:i + chunk_size] for i in range(0, len(l), chunk_size)]
print(chunks)
# [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]

วิธีอื่นๆ

1. ใช้ itertools.islice (memory efficient)

import itertools
def chunked(iterable, size):
    it = iter(iterable)
    while True:
        chunk = list(itertools.islice(it, size))
        if not chunk:
            break
        yield chunk

list(chunked(l, 4))
# [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]

2. ใช้ numpy (สำหรับ array ขนาดใหญ่)

import numpy as np
np.array(l).reshape(-1, 4).tolist()
# [[10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120]]

3. ใช้ more-itertools (third-party)

from more_itertools import chunked
list(chunked(l, 4))

แนะนำ: List comprehension กับ slice เรียบง่าย เร็ว และไม่ต้อง import เพิ่ม