Python 函数式编程:itertools 与 functools 的实用技巧
·
Python 函数式编程:itertools 与 functools 实用技巧
函数式编程通过无副作用函数和高阶函数处理数据,Python 的 itertools 和 functools 模块提供了核心工具。以下分模块介绍实用技巧:
一、itertools:高效迭代器工具
-
无限迭代器
count():生成无限等差数列from itertools import count counter = count(start=10, step=2) # 10, 12, 14...cycle():循环遍历序列cycler = cycle(['A', 'B']) # A→B→A→B...
-
组合生成器
product():计算笛卡尔积(替代嵌套循环)from itertools import product for x, y in product([1, 2], ['a', 'b']): print(x, y) # (1,a), (1,b), (2,a), (2,b)permutations():生成排列list(permutations('ABC', 2)) # [('A','B'), ('A','C'), ...]
-
数据切片与过滤
islice():惰性切片迭代器islice(count(), 5, 10) # 生成5~9的整数takewhile():条件截取takewhile(lambda x: x<5, [1,3,5,7]) # [1,3]
二、functools:高阶函数操作
-
偏函数(Partial)
冻结部分参数,创建新函数:from functools import partial pow_two = partial(pow, exp=2) # 固定指数为2 pow_two(3) # 9 (即3²) -
缓存优化
lru_cache加速递归函数:from functools import lru_cache @lru_cache(maxsize=128) def fib(n): return n if n<2 else fib(n-1)+fib(n-2) -
函数装饰器
wraps保留原函数元信息:from functools import wraps def logger(func): @wraps(func) # 保留func的名称和文档 def wrapper(*args): print(f"Calling {func.__name__}") return func(*args) return wrapper
三、综合应用示例
场景:生成坐标网格,并计算曼哈顿距离 $$d = |x_1 - x_2| + |y_1 - y_2|$$
from itertools import product, starmap
from functools import partial
# 生成2D网格坐标
points = product(range(3), repeat=2) # (0,0), (0,1), ... (2,2)
# 定义距离计算函数
def manhattan(a, b):
return sum(abs(a_i - b_i) for a_i, b_i in zip(a, b))
# 计算所有点到(1,1)的距离
dist_to_center = partial(manhattan, b=(1,1))
distances = starmap(dist_to_center, points)
print(list(distances)) # [2,1,2, 1,0,1, 2,1,2]
关键优势:
itertools:惰性计算节省内存,避免生成中间列表functools:通过函数组合减少重复代码,提升可读性- 两者结合可实现声明式编程风格,数据流清晰易维护
更多推荐


所有评论(0)