ภาพรวม
สร้าง N sublists ขนาด K โดยสุ่มจาก list หลัก ใช้ random.shuffle() และ generator function
ตัวอย่างโค้ด
from random import shuffle
def gen_random_list(source_list, k):
while True:
shuffle(source_list)
yield source_list[:k]
my_list = [12, 45, 76, 32, 45, 88, 99, 0, 1]
K, N = 4, 5
print("The list is:", my_list)
print("K =", K, "N =", N)
my_result = []
gen = gen_random_list(my_list, K)
for _ in range(N):
my_result.append(next(gen))
print("The result is:", my_result)
ผลลัพธ์ (ตัวอย่าง - สุ่มทุกครั้ง)
The list is: [12, 45, 76, 32, 45, 88, 99, 0, 1]
K = 4 N = 5
The result is: [[88, 76, 99, 12], [12, 99, 32, 76], [32, 76, 12, 99], [32, 45, 0, 12], [76, 0, 1, 45]]
คำอธิบาย
shuffle()สลับ list ต้นฉบับ inplaceyieldทำให้ฟังก์ชันเป็น generator- แต่ละครั้งที่
next()จะ shuffle ใหม่ และ yield K elements แรก - Note: source list ถูก mutate (เปลี่ยนไปตลอด) หากต้องการเก็บต้นฉบับ ใช้
source_list.copy()
วิธีที่ไม่ Mutate ต้นฉบับ (แนะนำ)
import random
def gen_random_list_safe(source_list, k):
pool = source_list.copy()
while True:
random.shuffle(pool)
yield pool[:k]
# หรือใช้ random.sample (ไม่ต้อง shuffle ทั้ง list)
def gen_random_sample(source_list, k):
while True:
yield random.sample(source_list, k)
# ใช้งาน
gen = gen_random_sample(my_list, K)
result = [next(gen) for _ in range(N)]
ประยุกต์ใช้
- Bootstrap sampling
- Random batch generation สำหรับ ML training
- Monte Carlo simulation