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 كـ حجج مدمجة لدوال أخرى، خاصة كمفاتيح 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= تبقى idiomatic وشائعة.
تتيح لك هذه الأدوات الوظيفية التعبير عن التحويلات والمرشحات بإيجاز.
بينما يمكن كتابة Python بأسلوب وظيفي، الاختيار idiomatic عادة هو comprehension على map/filter للوضوح، و built-in (sum, max, min) على reduce.
حيث تتألق lambdas فعلاً هو كدوال صغيرة مدمجة تُمرر إلى sort/max/min/filter كـ key.
فهم الاثنين معاً — ومعرفة تفضيل Python الidiomatic للـ comprehensions والـ built-ins — يساعدك على كتابة كود نظيف وidiomatic وقراءة الكود بأسلوب وظيفي الذي يظهر في مشاريع حقيقية.
مكتبة من أسئلة مقابلات تقنية المعلومات مع إجابات مفصّلة — من المبتدئ إلى المتقدم.
تبرع