🎯 学习目标

  • 理解函数式编程的核心思想
  • 掌握高阶函数的使用
  • 学会使用lambda表达式
  • 了解functools模块的实用工具

λ Lambda表达式

匿名函数

# 基本语法 # lambda 参数: 表达式 # 简单示例 square = lambda x: x ** 2 print(square(5)) # 25 add = lambda a, b: a + b print(add(3, 4)) # 7 # 条件表达式 max_val = lambda a, b: a if a > b else b print(max_val(3, 5)) # 5 # 在排序中使用 pairs = [(1, 'one'), (3, 'three'), (2, 'two')] pairs.sort(key=lambda x: x[0]) # [(1, 'one'), (2, 'two'), (3, 'three')]

高阶函数

map

# 对每个元素应用函数 nums = [1, 2, 3, 4, 5] squares = list(map( lambda x: x**2, nums )) # [1, 4, 9, 16, 25] # 等价于 squares = [x**2 for x in nums]

filter

# 过滤元素 nums = range(10) evens = list(filter( lambda x: x%2==0, nums )) # [0, 2, 4, 6, 8] # 等价于 evens = [x for x in nums if x%2==0]

reduce

from functools import reduce # 累积计算 nums = [1, 2, 3, 4, 5] total = reduce( lambda a, b: a + b, nums ) # 15 # 带初始值 total = reduce( lambda a, b: a + b, nums, 100 ) # 115

🔧 functools模块

from functools import partial, reduce, lru_cache, wraps # partial: 固定部分参数 def power(base, exponent): return base ** exponent square = partial(power, exponent=2) print(square(5)) # 25 # lru_cache: 缓存装饰器 @lru_cache(maxsize=128) def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) # 大幅提升递归性能 print(fibonacci(100)) # 瞬间完成 # wraps: 保留原函数信息 def my_decorator(func): @wraps(func) def wrapper(*args, **kwargs): print("Before") result = func(*args, **kwargs) print("After") return result return wrapper

🎯 函数式数据处理

链式处理

# 数据处理管道 data = [ {"name": "Alice", "age": 25, "score": 85}, {"name": "Bob", "age": 30, "score": 92}, {"name": "Charlie", "age": 25, "score": 78}, {"name": "David", "age": 35, "score": 88}, ] # 函数式风格 result = list( map(lambda x: x["name"], filter(lambda x: x["score"] > 80, sorted(data, key=lambda x: x["score"], reverse=True))) ) # ['Bob', 'David', 'Alice'] # 或使用列表推导式(更Pythonic) result = [x["name"] for x in sorted(data, key=lambda x: x["score"], reverse=True) if x["score"] > 80]
💡
何时使用函数式风格?
  • 适合:简单变换、一次性操作、作为高阶函数参数
  • 避免:复杂逻辑、可读性差的嵌套
  • 原则:Python推崇"显式优于隐式",列表推导式通常更清晰

📝 本节小结

  • • Lambda是简洁的匿名函数语法
  • • map/filter/reduce是函数式处理的核心
  • • functools提供了实用的函数工具
  • • Python推荐平衡函数式和面向对象风格