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

Comprehensions และ Generator Expressions

นักพัฒนา TypeScript ใช้ .map(), .filter(), และ .reduce() ต่อกันบน array วิธีนี้ใช้ได้ แต่ต้องสร้าง array กลางทางขึ้นมาใหม่ในแต่ละขั้น และไม่สามารถสร้าง Set หรือ object ได้โดยตรงตามธรรมชาติ Python มี comprehension syntax ฝังอยู่ในภาษาเลยสำหรับ 4 รูปแบบ ได้แก่ list, dict, set, และ generator แนวคิดหลักคือ [expression for item in iterable if condition]

กรณีที่พบบ่อยที่สุดคือการแปลง collection พร้อมกรองค่าไปด้วย ใน TypeScript ต้องเรียก method สองตัวแยกกัน แต่ใน Python เป็น expression เดียว

TypeScript
// TypeScript: chained .map() and .filter()
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// squares of even numbers
const 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.fromEntries
const words = ["hello", "world", "typescript"];
const wordLengths = Object.fromEntries(
words.map(w => [w, w.length])
);
console.log(wordLengths); // { hello: 5, world: 5, typescript: 10 }
Python
# Python: comprehensions for list, dict, set, and generator
numbers = list(range(1, 11))
# squares of even numbers — single expression
result = [n ** 2 for n in numbers if n % 2 == 0]
print(result) # [4, 16, 36, 64, 100]
# Dict comprehension — no need for Object.fromEntries
words = ["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 removed
unique_lengths = {len(word) for word in words}
print(unique_lengths) # {5, 6}

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 comprehension
squares = [x ** 2 for x in range(1, 6)]
print(squares)
# With filter condition
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
# Dict comprehension
word_lengths = {word: len(word) for word in ["hello", "world", "python"]}
print(word_lengths)
# Set comprehension -- unique values only
unique_lengths = {len(word) for word in ["hi", "hello", "hey", "world"]}
print(sorted(unique_lengths))
# Generator expression -- lazy
gen = (x ** 2 for x in range(5))
print(list(gen))
Syntax ใดให้ Python set comprehension?
ความแตกต่างหลักระหว่าง list comprehension กับ generator expression คืออะไร?
ถ้าวนซ้ำ generator expression สองครั้งจะเกิดอะไรขึ้น?
วิธีใดประหยัดหน่วยความจำที่สุดในการรวมค่ากำลังสองของเลข 0 ถึง 999?