Python教程18:Lambda函数与高阶函数
“简洁是智慧的灵魂。”
Lambda函数是Python中一种简洁的函数定义方式,配合map、filter等高阶函数,能让代码更加优雅。今天我们学习函数式编程的基础。
1. Lambda函数基础
什么是Lambda
Lambda是匿名函数,用于简单的单行函数:
1# 普通函数
2def square(x):
3 return x ** 2
4
5# Lambda函数
6square_lambda = lambda x: x ** 2
7
8print(square(5)) # 25
9print(square_lambda(5)) # 25
语法
1lambda 参数: 表达式
- 只能有一个表达式
- 自动返回表达式的值
- 不需要return
- 可以有多个参数
1# 多个参数
2add = lambda x, y: x + y
3print(add(3, 5)) # 8
4
5# 无参数
6greet = lambda: "Hello!"
7print(greet()) # Hello!
8
9# 默认参数
10power = lambda x, n=2: x ** n
11print(power(3)) # 9
12print(power(3, 3)) # 27
2. Lambda的实际应用
排序
1# 按元组第二个元素排序
2students = [
3 ("Alice", 85),
4 ("Bob", 92),
5 ("Charlie", 78)
6]
7
8# 使用lambda
9students.sorted(key=lambda x: x[1], reverse=True)
10print(students)
11# [('Bob', 92), ('Alice', 85), ('Charlie', 78)]
12
13# 字典排序
14scores = {"Alice": 85, "Bob": 92, "Charlie": 78}
15sorted_scores = dict(sorted(scores.items(), key=lambda x: x[1], reverse=True))
条件判断
1# 三元表达式
2max_val = lambda a, b: a if a > b else b
3print(max_val(10, 20)) # 20
4
5# 复杂条件
6grade = lambda score: 'A' if score >= 90 else ('B' if score >= 80 else 'C')
7print(grade(85)) # B
3. 高阶函数
高阶函数是接受函数作为参数或返回函数的函数。
map():映射
对序列中每个元素应用函数:
1# 平方
2numbers = [1, 2, 3, 4, 5]
3squares = list(map(lambda x: x**2, numbers))
4print(squares) # [1, 4, 9, 16, 25]
5
6# 多个序列
7a = [1, 2, 3]
8b = [4, 5, 6]
9sums = list(map(lambda x, y: x + y, a, b))
10print(sums) # [5, 7, 9]
11
12# 字符串处理
13names = ["alice", "bob", "charlie"]
14capitalized = list(map(str.capitalize, names))
15# ['Alice', 'Bob', 'Charlie']
filter():过滤
筛选满足条件的元素:
1# 过滤偶数
2numbers = range(1, 11)
3evens = list(filter(lambda x: x % 2 == 0, numbers))
4print(evens) # [2, 4, 6, 8, 10]
5
6# 过滤空字符串
7strings = ["hello", "", "world", "", "python"]
8non_empty = list(filter(lambda x: len(x) > 0, strings))
9# 或更简洁
10non_empty = list(filter(None, strings))
reduce():累积
从functools导入:
1from functools import reduce
2
3# 求和
4numbers = [1, 2, 3, 4, 5]
5total = reduce(lambda x, y: x + y, numbers)
6print(total) # 15
7
8# 求积
9product = reduce(lambda x, y: x * y, numbers)
10print(product) # 120
11
12# 找最大值
13max_num = reduce(lambda x, y: x if x > y else y, numbers)
14print(max_num) # 5
4. Lambda vs 列表推导式
很多时候两者可以互换:
1numbers = range(1, 11)
2
3# map + lambda
4squares1 = list(map(lambda x: x**2, numbers))
5
6# 列表推导式(更Pythonic)
7squares2 = [x**2 for x in numbers]
8
9# filter + lambda
10evens1 = list(filter(lambda x: x % 2 == 0, numbers))
11
12# 列表推导式
13evens2 = [x for x in numbers if x % 2 == 0]
推荐:简单情况用列表推导式,复杂逻辑用map/filter。
5. Lambda的限制
只能是单个表达式
1# 错误:不能有多条语句
2# bad = lambda x: (
3# y = x + 1 # SyntaxError
4# return y
5# )
6
7# 正确:用普通函数
8def process(x):
9 y = x + 1
10 z = y * 2
11 return z
不能包含赋值
1# 错误
2# f = lambda x: x = x + 1 # SyntaxError
3
4# 正确
5f = lambda x: x + 1
6. 实用技巧
结合sorted
1# 按长度排序
2words = ["python", "is", "awesome", "language"]
3sorted_words = sorted(words, key=lambda x: len(x))
4# ['is', 'python', 'awesome', 'language']
5
6# 多级排序
7students = [
8 {"name": "Alice", "age": 25, "score": 85},
9 {"name": "Bob", "age": 23, "score": 92},
10 {"name": "Charlie", "age": 25, "score": 78}
11]
12
13# 先按年龄,再按分数
14sorted_students = sorted(students, key=lambda x: (x["age"], -x["score"]))
事件处理(GUI编程)
1# 简化回调函数
2button.config(command=lambda: print("Button clicked"))
3
4# 带参数的回调
5for i in range(5):
6 button = Button(text=str(i))
7 button.config(command=lambda x=i: handle_click(x))
7. 何时使用Lambda
适合:
- 简单的单行逻辑
- 作为参数传递
- 临时使用,不需要命名
不适合:
- 复杂逻辑
- 需要复用
- 需要文档说明
1# 适合lambda
2sorted(numbers, key=lambda x: abs(x))
3
4# 不适合lambda(用def)
5def complex_process(x):
6 """复杂的处理逻辑"""
7 result = x * 2
8 result = result + 10
9 if result > 100:
10 result = 100
11 return result
8. 小结
今天我们学习了:
- Lambda函数:
lambda x: x**2 - 高阶函数:
- map():映射转换
- filter():条件过滤
- reduce():累积计算
- 对比:Lambda vs 列表推导式
- 限制:单表达式、不能赋值
- 使用场景:简单逻辑、回调函数
Lambda和高阶函数让代码更函数式、更简洁,但要注意可读性。
练习题:
- 用lambda和filter找出列表中所有质数
- 用reduce计算阶乘
- 对字典列表按多个字段排序
本文代码示例:
关注公众号:极客老墨
更多 AI 应用开发、工程实践和效率工具分享,欢迎扫码关注。
