lambda คือฟังก์ชันขนาดเล็ก ไม่มีชื่อ และมีนิพจน์เดียว map, filter และ reduce เป็นเครื่องมือเชิงฟังก์ชันที่ใช้ฟังก์ชันกับ iterable โดยรวมกันเพื่อเปิดใช้งานสไตล์เชิงฟังก์ชัน — แม้ว่า Python มักจะชอบ comprehensions สำหรับงานเดียวกัน
lambda คือฟังก์ชันขนาดเล็ก ไม่มีชื่อ และมีนิพจน์เดียว map, filter และ reduce เป็นเครื่องมือเชิงฟังก์ชันที่ใช้ฟังก์ชันกับ iterable โดยรวมกันเพื่อเปิดใช้งานสไตล์เชิงฟังก์ชัน — แม้ว่า Python มักจะชอบ comprehensions สำหรับงานเดียวกัน
# a lambda is a one-line function with no name
square = lambda x: x ** 2
square(5) # 25
# equivalent named function:
def square(x): return x ** 2
Lambdas สดใส ซึ่งเป็น inline arguments สำหรับฟังก์ชันอื่น โดยเฉพาะอย่างยิ่งเป็นกุญแจ sort/filter:
people.sort(key=lambda p: p.age) # sort by an attribute
sorted(words, key=lambda w: len(w)) # sort by length
max(items, key=lambda x: x.score) # find max by a criterion
nums = [1, 2, 3, 4]
list(map(lambda x: x ** 2, nums)) # [1, 4, 9, 16]
# more Pythonic alternative — a comprehension:
[x ** 2 for x in nums] # [1, 4, 9, 16]
list(filter(lambda x: x % 2 == 0, nums)) # [2, 4]
# comprehension equivalent:
[x for x in nums if x % 2 == 0] # [2, 4]
from functools import reduce
reduce(lambda acc, x: acc + x, nums, 0) # 10 (sum)
# but built-ins are clearer when they exist:
sum(nums) # 10
For map/filter, COMPREHENSIONS are usually more readable and idiomatic:
map(f, xs) → [f(x) for x in xs]
filter(pred, xs) → [x for x in xs if pred(x)]
Lambdas are best for short inline keys (sort/max/filter), NOT complex logic.
Guido (ผู้สร้าง Python) และชุมชนโดยทั่วไปชอบ comprehensions มากกว่า map/filter เพื่อความสามารถในการอ่าน reduce ถูกย้ายออกจาก builtins ด้วยซ้ำ แต่ lambdas เป็นฟังก์ชัน key= ยังคงเป็นสำนวนและทั่วไป
เครื่องมือเชิงฟังก์ชันเหล่านี้ช่วยให้คุณสามารถแสดงการแปลงและตัวกรองอย่างกระชับ
แม้ว่า Python สามารถ เขียนแบบฟังก์ชันได้ แต่ตัวเลือกสำนวนมักจะเป็น comprehension มากกว่า map/filter เพื่อความสามารถในการอ่าน และ built-in (sum, max, min) มากกว่า reduce
สถานที่ที่ lambdas ใช้ได้ดีจริงๆ คือเมื่อเป็นฟังก์ชัน inline เล็กๆ ที่ผ่านไปยัง sort/max/min/filter เป็น key
การเข้าใจทั้งสอง — และรู้ว่า Pythonic preference สำหรับ comprehensions และ built-ins — ช่วยให้คุณเขียนโค้ดที่สะอาด เป็นสำนวน และอ่านโค้ดเชิงฟังก์ชันที่ปรากฏในโครงการจริง