lambda 是一个小的、匿名的、单表达式函数。map、filter 和 reduce 是在 iterable 上应用函数的 functional tools。它们一起启用了函数式风格——尽管 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 甚至被移出了内置函数。但 lambdas 作为 key= 函数仍然是习惯用法且常见的。
这些 functional tools 让你能够简洁地表达转换和过滤。
虽然 Python 可以 以函数式风格编写,但习惯用法通常是为了可读性而使用 comprehension 而非 map/filter,以及使用内置函数(sum、max、min)而非 reduce。
Lambdas 真正闪耀的地方是作为传递给 sort/max/min/filter 的小内联函数作为 key。
理解两者——并知道 Pythonic 对 comprehensions 和内置函数的偏好——帮助你编写干净、习惯用法的代码,并理解出现在实际项目中的函数式风格代码。
一个包含详细解答的 IT 面试题库——从初级到高级。
捐赠