Comprehensions และ Generator Expressions
Syntax เดียวสำหรับการแปลง collection ทั้งหมด
หัวข้อที่มีชื่อว่า “Syntax เดียวสำหรับการแปลง collection ทั้งหมด”นักพัฒนา TypeScript ใช้ .map(), .filter(), และ .reduce() ต่อกันบน array วิธีนี้ใช้ได้ แต่ต้องสร้าง array กลางทางขึ้นมาใหม่ในแต่ละขั้น และไม่สามารถสร้าง Set หรือ object ได้โดยตรงตามธรรมชาติ Python มี comprehension syntax ฝังอยู่ในภาษาเลยสำหรับ 4 รูปแบบ ได้แก่ list, dict, set, และ generator แนวคิดหลักคือ [expression for item in iterable if condition]
List comprehension เทียบกับ map/filter
หัวข้อที่มีชื่อว่า “List comprehension เทียบกับ map/filter”กรณีที่พบบ่อยที่สุดคือการแปลง collection พร้อมกรองค่าไปด้วย ใน TypeScript ต้องเรียก method สองตัวแยกกัน แต่ใน Python เป็น expression เดียว
// TypeScript: chained .map() and .filter()const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// squares of even numbersconst result = numbers .filter(n => n % 2 === 0) .map(n => n ** 2);
console.log(result); // [4, 16, 36, 64, 100]
// Building an object from an array requires reduce or Object.fromEntriesconst words = ["hello", "world", "typescript"];const wordLengths = Object.fromEntries( words.map(w => [w, w.length]));console.log(wordLengths); // { hello: 5, world: 5, typescript: 10 }# Python: comprehensions for list, dict, set, and generator
numbers = list(range(1, 11))
# squares of even numbers — single expressionresult = [n ** 2 for n in numbers if n % 2 == 0]print(result) # [4, 16, 36, 64, 100]
# Dict comprehension — no need for Object.fromEntrieswords = ["hello", "world", "python"]word_lengths = {word: len(word) for word in words}print(word_lengths) # {'hello': 5, 'world': 5, 'python': 6}
# Set comprehension — duplicates are automatically removedunique_lengths = {len(word) for word in words}print(unique_lengths) # {5, 6}ครบทั้ง 4 รูปแบบ
หัวข้อที่มีชื่อว่า “ครบทั้ง 4 รูปแบบ”List comprehension — สร้าง list แบบ eager:
squares = [x ** 2 for x in range(1, 6)]# [1, 4, 9, 16, 25]Dict comprehension — สร้าง dict:
word_lengths = {word: len(word) for word in ["hello", "world", "python"]}# {'hello': 5, 'world': 5, 'python': 6}Set comprehension — สร้าง set (ไม่มีค่าซ้ำ):
unique_lengths = {len(word) for word in ["hi", "hello", "hey", "world"]}# {2, 3, 5}Generator expression — สร้าง lazy generator (ใช้วงเล็บ ไม่ใช่ bracket):
gen = (x ** 2 for x in range(5))# Nothing is computed yet. Values are produced only when iterated.print(list(gen)) # [0, 1, 4, 9, 16]Syntax เหมือนกันทุกรูปแบบ ต่างกันแค่ตัวคั่นด้านนอก: [] สำหรับ list, {} พร้อม colon สำหรับ dict, {} ไม่มี colon สำหรับ set, และ () สำหรับ generator
ลองทดสอบ
หัวข้อที่มีชื่อว่า “ลองทดสอบ”# List comprehensionsquares = [x ** 2 for x in range(1, 6)]print(squares)
# With filter conditionevens = [x for x in range(10) if x % 2 == 0]print(evens)
# Dict comprehensionword_lengths = {word: len(word) for word in ["hello", "world", "python"]}print(word_lengths)
# Set comprehension -- unique values onlyunique_lengths = {len(word) for word in ["hi", "hello", "hey", "world"]}print(sorted(unique_lengths))
# Generator expression -- lazygen = (x ** 2 for x in range(5))print(list(gen))Loading Python runtime (first run only)…