ลิสต์เป็นคอลเลกชันที่มีลำดับและเปลี่ยนแปลงได้ เขียนด้วยวงเล็บเหลี่ยม เข้าถึงได้โดยดัชนี โดย -1 คือตัวสุดท้าย สามารถ slice ได้เพื่อดึงช่วงข้อมูล
ตัวอย่างโค้ด
1. ใช้ List Comprehension (แนะนำ)
# Triplets จากลิสต์คำ
list_of_words = ['I', 'am', 'Vishesh', 'and', 'I', 'like', 'Python', 'programming']
# ใช้ list comprehension สร้าง sliding window ขนาด 3
List = [list_of_words[i:i + 3] for i in range(len(list_of_words) - 2)]
print(List)
2. ใช้ Loop ทั่วไป (Naive Method)
list_of_words = ['I', 'am', 'Vishesh', 'and', 'I', 'like', 'Python', 'programming']
out = []
length = len(list_of_words)
for z in range(0, length - 2):
temp = []
temp.append(list_of_words[z])
temp.append(list_of_words[z + 1])
temp.append(list_of_words[z + 2])
out.append(temp)
print(out)
ผลลัพธ์
[['I', 'am', 'Vishesh'], ['am', 'Vishesh', 'and'], ['Vishesh', 'and', 'I'], ['and', 'I', 'like'], ['I', 'like', 'Python'], ['like', 'Python', 'programming']]
สรุปและขยาย
Generalized Function สำหรับ Window Size ใดๆ
def sliding_window(lst, window_size):
"""สร้าง sliding windows จากลิสต์"""
return [lst[i:i + window_size] for i in range(len(lst) - window_size + 1)]
# ตัวอย่างใช้งาน
words = ['I', 'am', 'Vishesh', 'and', 'I', 'like', 'Python', 'programming']
print(sliding_window(words, 3)) # triplets
print(sliding_window(words, 2)) # pairs
print(sliding_window(words, 4)) # quadruplets
ใช้ itertools (สำหรับ memory efficient)
from itertools import islice
def sliding_window_iter(iterable, window_size):
"""Generator version - ประหยัดหน่วยความจำ"""
it = iter(iterable)
window = list(islice(it, window_size))
if len(window) == window_size:
yield window
for item in it:
window = window[1:] + [item]
yield window
# ใช้งาน
for window in sliding_window_iter(words, 3):
print(window)
กรณีใช้งานทั่วไป
- N-gram ใน NLP
- Time series analysis (rolling window)
- Feature engineering สำหรับ ML
- Pattern matching ใน sequences