Lambda 函数
Anonymous 函数使用 lambda: 语法, use 使用映射/筛选/排序, and 当到 avoid 它们.
你将学到
- 编写 lambda 表达式 for 简单函数
- Use lambdas 使用映射(), 筛选(), and 排序()
- 理解 lambda limitations and 作用域
- 选择之间 lambda and def appropriately
- Apply lambdas as 键函数 in 排序
概念讲解
What Is a Lambda?
lambda 是一种 small anonymous function defined in a single expression. It is useful for short, throwaway functions that you do not need to name:
# Regular function
def square(x):
return x ** 2
# Equivalent lambda
square = lambda x: x ** 2
print(square(5)) # 25 (works the same)
The syntax is lambda 参数: 表达式. The expression is evaluated and returned automatically — there is no 返回 keyword. Lambdas can have multiple parameters but only one expression.
Multiple Parameters
add = lambda a, b: a + b
print(add(3, 4)) # 7
# Default values work too
greet = lambda name, greeting="Hello": f"{greeting}, {name}!"
print(greet("Ada")) # Hello, Ada!
Using Lambda with map()
映射() applies a function to every item in an iterable:
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
# [1, 4, 9, 16, 25]
# Equivalent list comprehension (often preferred)
squared = [x ** 2 for x in numbers]
In modern Python, list comprehensions are usually preferred over 映射() with a lambda — they are more readable and often faster. However, 映射() can be cleaner when you already have a named function.
Using Lambda with filter()
筛选() keeps items where the function returns True:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4, 6, 8, 10]
# Equivalent list comprehension (preferred)
evens = [x for x in numbers if x % 2 == 0]
Again, list comprehensions are generally preferred for readability.
Using Lambda with sorted() — The Best Use Case
The most common and justified use of lambda is as a key function in sorting:
students = [
{"name": "Ada", "grade": 85},
{"name": "Bob", "grade": 92},
{"name": "Cy", "grade": 78},
]
# Sort by grade (descending)
students_sorted = sorted(students, key=lambda s: s["grade"], reverse=True)
# Sort by name length
by_name_length = sorted(students, key=lambda s: len(s["name"]))
# Sort tuples by second element
pairs = [(1, 3), (2, 1), (3, 2)]
sorted_pairs = sorted(pairs, key=lambda p: p[1])
This is where lambdas shine — a short, inline function that extracts the sort key. Using a named def for a one-line key extractor would be unnecessarily verbose.
Using Lambda with reduce()
functools.reduce() applies a function cumulatively to reduce an iterable to a single value:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda a, b: a * b, numbers)
# 120 (1*2*3*4*5)
# Equivalent without reduce:
product = 1
for n in numbers:
product *= n
reduce() is less common and can be hard to read — a regular loop is often clearer.
Lambda Limitations
Lambdas are restricted to a single expression — no statements, no assignments, no multi-line logic:
# This is INVALID — lambdas cannot have statements
# lambda x: if x > 0: return x else: return -x
# Use a regular function instead:
def abs_val(x):
if x > 0:
return x
return -x
Lambdas cannot contain:
如果statements (use ternaryx 如果 cond else yinstead)for/虽然loopstry/except- Variable assignments (no
=in the body) - Multiple expressions
Late Binding Gotcha
Lambdas capture variables by reference, not by value. This causes a classic bug in loops:
# BUG — all lambdas return 4!
funcs = [lambda: i for i in range(5)]
print([f() for f in funcs]) # [4, 4, 4, 4, 4]
# FIX — use a default argument to capture the current value
funcs = [lambda i=i: i for i in range(5)]
print([f() for f in funcs]) # [0, 1, 2, 3, 4]
The default argument i=i evaluates at definition time, capturing the current value of i.
When to Use Lambda vs def
Use lambda when:
- The function is a single simple expression
- It is used inline (as a key, callback, or argument to map/filter)
- You do not need to reuse it or give it a name
Use def when:
- The function has multiple statements
- You need a docstring
- The function is reused or needs a name for clarity
- The logic is complex
PEP 8: "Always use a def statement instead of an assignment statement that binds a lambda expression directly to a name." In other words, do not write f = lambda x: x + 1 — write def f(x): return x + 1 instead. Assigning a lambda to a name defeats its purpose.
示例代码
# Basic lambda
square = lambda x: x ** 2
print(square(5)) # 25
# Multiple parameters
add = lambda a, b: a + b
print(add(3, 4)) # 7
# Lambda as a sort key — the best use case
students = [
{"name": "Ada", "grade": 85},
{"name": "Bob", "grade": 92},
{"name": "Cy", "grade": 78},
]
# Sort by grade descending
by_grade = sorted(students, key=lambda s: s["grade"], reverse=True)
for s in by_grade:
print(f" {s['name']}: {s['grade']}")
# Sort by name length
by_len = sorted(students, key=lambda s: len(s["name"]))
print([s["name"] for s in by_len])
# map() with lambda
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(f"Squared: {squared}")
# filter() with lambda
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Evens: {evens}")
# reduce() with lambda
from functools import reduce
product = reduce(lambda a, b: a * b, numbers)
print(f"Product: {product}") # 120
# Late binding fix — default argument
funcs = [lambda i=i: i for i in range(5)]
print([f() for f in funcs]) # [0, 1, 2, 3, 4]
# Practical: sort strings case-insensitively
words = ["Banana", "apple", "Cherry", "date"]
sorted_words = sorted(words, key=lambda w: w.lower())
print(sorted_words) # ['apple', 'Banana', 'Cherry', 'date']
Shows 基础 lambdas, 多个参数, 键函数 use 情况使用排序(), 映射/筛选/reduce, late-binding gotcha and 它的 fix, and practical 情况-insensitive 排序.
动手试一试
- 文本计数器
Lambdas 是 useful for transforming counted 文本 statistics.
- 情况 Converter
Lambda 键函数能 排序通过情况-converted 值.
常见错误
错误写法
Assigning lambda 到变量 name: f = lambda x: x + 1
正确做法
PEP 8 says: 总是 use def 语句相反的 binding lambda 到 name. 编写 'def f(x): 返回 x + 1' 相反. Lambdas 是 meant for inline use (as 键函数 or 回调), 不 as named 函数.
错误写法
late binding bug: [lambda: i for i in 范围(5)] 所有返回 4
正确做法
Lambdas capture 变量通过引用, 所以所有函数 see 最终循环值. Fix 使用默认实参: [lambda i=i: i for i in 范围(5)]. 默认是 evaluated at 定义时间, capturing current 值.
相关资源
相关速查表
- Python Cheatsheet
Lambda 语法, 映射/筛选/reduce, and 键函数.
练习 Lambda 函数
4 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。