匿名函数(Lambda) #

lambda是创建匿名函数的简洁方式。

一、基本语法 #

python
lambda arguments: expression

二、基本用法 #

python
# 普通函数
def add(a, b):
    return a + b

# lambda等价写法
add = lambda a, b: a + b

print(add(3, 5))  # 8

# 单参数
square = lambda x: x ** 2
print(square(5))  # 25

# 无参数
get_pi = lambda: 3.14159
print(get_pi())  # 3.14159

三、常见应用场景 #

3.1 排序 #

python
students = [
    {"name": "Tom", "age": 25},
    {"name": "Jerry", "age": 30},
    {"name": "Alice", "age": 28}
]

# 按age排序
sorted_students = sorted(students, key=lambda x: x["age"])

# 按name排序
sorted_students = sorted(students, key=lambda x: x["name"])

3.2 filter #

python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 过滤偶数
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6, 8, 10]

# 过滤大于5的数
greater = list(filter(lambda x: x > 5, numbers))

3.3 map #

python
numbers = [1, 2, 3, 4, 5]

# 平方
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # [1, 4, 9, 16, 25]

# 两列表相加
a = [1, 2, 3]
b = [10, 20, 30]
sums = list(map(lambda x, y: x + y, a, b))
print(sums)  # [11, 22, 33]

3.4 reduce #

python
from functools import reduce

numbers = [1, 2, 3, 4, 5]

# 求和
total = reduce(lambda x, y: x + y, numbers)
print(total)  # 15

# 求积
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 120

3.5 字典排序 #

python
scores = {"Tom": 85, "Jerry": 90, "Alice": 88}

# 按值排序
sorted_scores = sorted(scores.items(), key=lambda x: x[1])
print(sorted_scores)  # [('Tom', 85), ('Alice', 88), ('Jerry', 90)]

# 按键排序
sorted_scores = sorted(scores.items(), key=lambda x: x[0])

四、条件表达式 #

python
# 条件判断
is_even = lambda x: "偶数" if x % 2 == 0 else "奇数"
print(is_even(4))  # 偶数
print(is_even(5))  # 奇数

# 取绝对值
abs_value = lambda x: x if x >= 0 else -x
print(abs_value(-5))  # 5

五、限制 #

python
# lambda只能是单个表达式
# 不能包含语句
# lambda x: print(x); return x  # 错误

# 复杂逻辑使用普通函数
def process(x):
    result = x * 2
    if result > 10:
        return result
    return result + 1

六、立即调用 #

python
# 立即调用的lambda
result = (lambda x, y: x + y)(3, 5)
print(result)  # 8

七、总结 #

特点 说明
语法 lambda args: expression
匿名 没有函数名
单表达式 只能包含一个表达式
返回值 自动返回表达式结果

适用场景:

  • 简单的一次性函数
  • 作为sortedfiltermap的参数
  • 回调函数
最后更新:2026-03-16