Comprehensions
Comprehension คืออะไร?
หัวข้อที่มีชื่อว่า “Comprehension คืออะไร?”comprehension คือนิพจน์ที่กระชับและอ่านง่าย ใช้สร้าง collection ใหม่โดยการแปลงหรือกรอง iterable Python มีสามรูปแบบ: list, dict และ set comprehension
List comprehensions
หัวข้อที่มีชื่อว่า “List comprehensions”รูปแบบทั่วไปคือ:
[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
Nested comprehensions
หัวข้อที่มีชื่อว่า “Nested comprehensions”สามารถซ้อน 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)]Dict comprehensions
หัวข้อที่มีชื่อว่า “Dict comprehensions”ใช้ {} และ 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}Set comprehensions
หัวข้อที่มีชื่อว่า “Set comprehensions”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))Loading Python runtime (first run only)…