Python3 高阶函数:函数式编程的核心工具
高阶函数(Higher-order function)是函数式编程的核心概念,指接受函数作为参数或返回函数作为结果的函数。Python 3 内置了多个实用的高阶函数,如 map()、filter()、reduce() 等,它们能大幅简化代码,提高可读性和效率。本文从基础概念到实战应用,全面讲解 Python 高阶函数的使用。
高阶函数的基本概念
1. 函数作为参数
在 Python 中,函数是第一类对象(First-class object),可以像其他数据类型一样被传递。当一个函数接受另一个函数作为参数时,它就是高阶函数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| def square(x): return x **2
def apply_func(func, numbers): result = [] for num in numbers: result.append(func(num)) return result
nums = [1, 2, 3, 4] print(apply_func(square, nums))
|
2. 函数作为返回值
高阶函数还可以返回一个函数,实现 “动态生成函数” 的效果。
1 2 3 4 5 6 7 8 9 10 11 12 13
| def make_multiplier(factor): def multiplier(x): return x * factor return multiplier
double = make_multiplier(2) triple = make_multiplier(3)
print(double(5)) print(triple(5))
|
Python 内置高阶函数
Python 标准库提供了多个实用的高阶函数,以下是最常用的几个:
1.map (func, iterable):映射序列元素
map() 接收一个函数和一个可迭代对象(如列表、元组),将函数应用到每个元素上,返回一个迭代器(需转换为列表查看结果)。
基本用法:
1 2 3 4 5 6 7 8 9
| def to_str(n): return str(n)
numbers = [1, 2, 3, 4] str_numbers = map(to_str, numbers)
print(list(str_numbers))
|
配合匿名函数(lambda):
1 2 3 4 5
| numbers = [1, 2, 3, 4] squares = map(lambda x: x** 2, numbers)
print(list(squares))
|
多序列映射:
map() 可接收多个可迭代对象,函数需对应接收多个参数:
1 2 3 4 5 6
| a = [1, 2, 3] b = [4, 5, 6] sums = map(lambda x, y: x + y, a, b)
print(list(sums))
|
2. filter(func, iterable): 过滤序列元素
filter() 接收一个 “判断函数” 和可迭代对象,保留函数返回 True 的元素,返回迭代器。
基本用法:
1 2 3 4 5 6 7 8 9
| def is_even(n): return n % 2 == 0
numbers = [1, 2, 3, 4, 5, 6] evens = filter(is_even, numbers)
print(list(evens))
|
配合匿名函数:
1 2 3 4 5
| numbers = [-2, -1, 0, 1, 2, 3] positives = filter(lambda x: x > 0, numbers)
print(list(positives))
|
3. reduce(func, iterable[, initial]): 归并序列元素
reduce() 接收一个 “二元函数”(接收两个参数)和可迭代对象,从左到右累计应用函数,最终将序列归并为单个值。
注意:reduce() 在 Python 3 中移至 functools 模块,需先导入。
基本用法:
1 2 3 4 5 6 7 8 9 10 11
| from functools import reduce
def add(x, y): return x + y
numbers = [1, 2, 3, 4] total = reduce(add, numbers)
print(total)
|
配合匿名函数:
1 2 3 4 5 6 7
| from functools import reduce
numbers = [1, 2, 3, 4] product = reduce(lambda x, y: x * y, numbers)
print(product)
|
指定初始值:
1 2 3 4 5 6 7
| from functools import reduce
numbers = [1, 2, 3, 4] total = reduce(lambda x, y: x + y, numbers, 10)
print(total)
|
4. sorted(iterable, key=None, reverse=False): 排序
sorted() 是高阶函数,通过 key 参数接收一个函数,根据函数返回值对元素排序,返回新的排序后的列表(不修改原序列)。
基本用法:
1 2 3 4 5
| fruits = ["apple", "banana", "cherry", "date"] sorted_fruits = sorted(fruits)
print(sorted_fruits)
|
按自定义规则排序(key 参数):
1 2 3 4 5 6 7 8 9 10 11
| fruits = ["apple", "banana", "cherry", "date"] sorted_by_length = sorted(fruits, key=lambda s: len(s))
print(sorted_by_length)
numbers = [-3, 1, -2, 5] sorted_by_abs = sorted(numbers, key=lambda x: abs(x))
print(sorted_by_abs)
|
逆序排序(reverse=True):
1 2 3 4 5
| scores = [85, 92, 78, 90] sorted_desc = sorted(scores, reverse=True)
print(sorted_desc)
|
高阶函数的实际应用场景
1. 数据转换与清洗
使用 map() 和 filter() 处理列表数据,实现简洁的数据转换和过滤:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| raw_data = ["12", "34", "abc", "56", "7.8", "90"]
def is_int(s): try: int(s) return True except ValueError: return False
valid_strs = filter(is_int, raw_data)
numbers = map(int, valid_strs)
print(list(numbers))
|
2. 函数复用与装饰器基础
高阶函数返回函数的特性,是实现 “装饰器(Decorator)” 的基础。装饰器用于在不修改原函数代码的前提下,为函数添加额外功能(如日志、计时、权限校验等)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| def log_decorator(func): def wrapper(*args, **kwargs): print(f"调用函数:{func.__name__},参数:{args}, {kwargs}") result = func(*args, **kwargs) print(f"函数 {func.__name__} 返回:{result}") return result return wrapper
@log_decorator def add(a, b): return a + b
add(2, 3)
|
1 2 3
| @log_decorator def add(): pass
|
等价于
1
| func = log_decorator(add)
|
装饰器就是 语法糖,让 func = log_decorator(add) 更优雅
如果有多个装饰器,离函数最近的装饰器先装饰,然后外面的装饰器在进行装饰,由内到外的装饰过程
3. 实现策略模式
策略模式(Strategy Pattern)通过高阶函数动态选择算法,提高代码灵活性:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| def calculate_total_normal(price, quantity): """正常计价:单价×数量""" return price * quantity
def calculate_total_discount(price, quantity): """折扣计价:满3件打8折""" total = price * quantity return total * 0.8 if quantity >= 3 else total
def calculate_total_promotion(price, quantity): """促销计价:第二件半价""" if quantity == 1: return price return price + (quantity - 1) * (price * 0.5)
def calculate(price, quantity, strategy): return strategy(price, quantity)
print(calculate(100, 2, calculate_total_normal)) print(calculate(100, 3, calculate_total_discount)) print(calculate(100, 2, calculate_total_promotion))
|
高阶函数 vs 列表推导式:如何选择?
在很多场景下,高阶函数(如 map()、filter())和列表推导式可以实现相同功能,选择依据如下:
| 方式 |
优势 |
劣势 |
适用场景 |
高阶函数(map/filter) |
函数式编程风格,适合链式调用 |
复杂逻辑需额外定义函数,可读性可能下降 |
简单转换 / 过滤,或与其他高阶函数组合 |
| 列表推导式 |
语法简洁,可读性高,支持条件判断 |
不适合复杂函数逻辑 |
大多数数据转换 / 过滤场景 |
示例对比:
1 2 3 4 5 6 7
| squares_map = list(map(lambda x: x** 2, range(1, 11)))
squares_list = [x **2 for x in range(1, 11)]
print(squares_map == squares_list)
|
实战案例:数据处理流水线
结合多个高阶函数,实现一个数据处理流水线,完成 “读取→清洗→转换→聚合” 全流程:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| from functools import reduce
raw_scores = ["Alice:90", "Bob:85", "Charlie:abc", "David:95", "Eve:78"]
def parse_score(s): try: name, score = s.split(":") return (name, int(score)) except (ValueError, TypeError): return None
valid_data = filter(None, map(parse_score, raw_scores))
scores = list(map(lambda x: x[1], valid_data)) average = reduce(lambda x, y: x + y, scores) / len(list(scores))
print(f"有效分数的平均分:{average:.2f}")
|
总结
高阶函数是 Python 函数式编程的核心,掌握它们能显著提升代码质量:
1.核心概念:函数作为参数或返回值,实现灵活的逻辑组合;
2.内置高阶函数:
map():映射转换,适合批量处理元素;
filter():过滤筛选,保留符合条件的元素;
reduce():归并聚合,将序列缩减为单个值;
sorted():自定义排序,通过 key 控制排序规则;
3.应用场景 :数据处理、函数装饰器、策略模式等,尤其适合处理集合数据;
4.最佳实践:简单逻辑优先使用内置高阶函数或列表推导式,复杂逻辑结合自定义高阶函数。
高阶函数的本质是 “用函数抽象通用逻辑”,通过将变化的部分(具体函数)作为参数传入,实现代码的复用和扩展,是编写简洁、高效 Python 代码的重要工具