ข้ามไปยังเนื้อหา

Comprehensions

comprehension คือนิพจน์ที่กระชับและอ่านง่าย ใช้สร้าง collection ใหม่โดยการแปลงหรือกรอง iterable Python มีสามรูปแบบ: list, dict และ set comprehension

รูปแบบทั่วไปคือ:

[expression for item in iterable]
[expression for item in iterable if condition]
squares = [x**2 for x in range(1, 8)]
# [1, 4, 9, 16, 25, 36, 49]
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

ทั้งสองตัวอย่างเทียบเท่ากับ for loop ที่ append ลง list แต่กระชับกว่าและมักเร็วกว่าเพราะการวนซ้ำเกิดใน C ไม่ใช่ bytecode

สามารถซ้อน for หลายตัวเพื่อวนซ้ำข้าม combination ประโยค for อ่านจากซ้ายไปขวา — for ซ้ายสุดเป็น outer loop

pairs = [
(x, y)
for x in range(1, 4)
for y in range(1, 4)
if x != y
]
# [(1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2)]

ใช้ {} และ syntax key: value

word_len = {word: len(word) for word in ['apple', 'banana', 'cherry']}
# {'apple': 5, 'banana': 6, 'cherry': 6}

Dict comprehension เป็นวิธีที่สะอาดสำหรับการกลับ mapping, กรอง entry หรือแปลง value:

prices = {'apple': 1.5, 'banana': 0.75, 'cherry': 3.0}
expensive = {k: v for k, v in prices.items() if v >= 1.5}
# {'apple': 1.5, 'cherry': 3.0}

Syntax เหมือน list comprehension แต่ใช้ {} ค่าซ้ำถูกลบออกอัตโนมัติ

unique_lens = {len(word) for word in ['apple', 'banana', 'cherry', 'date']}
# {4, 5, 6} (ไม่รับประกันลำดับ)
# --- list comprehension ---
squares = [x**2 for x in range(1, 8)]
print('squares:', squares)
evens = [x for x in range(20) if x % 2 == 0]
print('evens:', evens)
# --- nested comprehension ---
pairs = [(x, y) for x in range(1, 4) for y in range(1, 4) if x != y]
print('pairs:', pairs)
# --- dict comprehension ---
word_len = {word: len(word) for word in ['apple', 'banana', 'cherry']}
print('word lengths:', word_len)
# --- set comprehension ---
unique_lens = {len(word) for word in ['apple', 'banana', 'cherry', 'date']}
print('unique lengths:', sorted(unique_lens))
`[x**2 for x in range(4)]` ได้ผลลัพธ์อะไร?
จะเพิ่ม filter ใน list comprehension ได้อย่างไร?
Comprehension ประเภทใดที่ลบค่าซ้ำออกอัตโนมัติ?
ใน `[f(x, y) for x in A for y in B]` loop ใดเป็น OUTER loop?