6个月Python学习计划 Day 15 - 函数式编程、高阶函数、生成器/迭代器
第三周 Day 1
🎯 今日目标
- 掌握 Python 中函数式编程的核心概念
- 熟悉 map()、filter()、reduce() 等高阶函数
- 结合 lambda 和 列表/字典 进行数据处理练习
- 了解生成器与迭代器基础,初步掌握惰性计算概念
🧠 函数式编程基础
函数式编程是一种“将函数作为数据处理工具”的风格,强调表达式、不可变性和链式操作。
🛠 常用高阶函数
1️⃣ map(func, iterable):将函数应用于序列的每个元素
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
print(squares) # 输出 [1, 4, 9, 16]
2️⃣ filter(func, iterable):过滤序列中符合条件的元素
nums = [5, 8, 12, 3, 7]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even) # 输出 [8, 12]
reduce(func, iterable):连续两两执行函数(需导入)
from functools import reducenums = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, nums)
print(total) # 输出 10
🔁 生成器 Generator
生成器是一种惰性迭代器,只在需要时计算结果,节省内存。
def countdown(n):while n > 0:yield nn -= 1for i in countdown(5):print(i)
🔄 迭代器 Iterator
任何实现了 iter() 和 next() 方法的对象都可以被称为迭代器。
lst = iter([1, 2, 3])
print(next(lst)) # 输出 1
print(next(lst)) # 输出 2
🧪 今日练习任务
✅ 练习1:用 map 和 lambda 对列表每个数平方
nums = [2, 4, 6, 8]
result = list(map(lambda x: x**2, nums))
print(result)
✅ 练习2:用 filter 筛选出长度大于3的字符串
words = ['hi', 'hello', 'python', 'no']
filtered = list(filter(lambda w: len(w) > 3, words))
print(filtered)
✅ 练习3:实现一个生成器,生成前 N 个偶数
def even_gen(n):for i in range(n):yield i * 2print(list(even_gen(5))) # 输出 [0, 2, 4, 6, 8]
📌 今日总结
内容 | 说明 |
---|---|
函数式编程入门 | 高阶函数 map/filter/reduce |
惰性计算 | 生成器节省内存,适合大数据处理 |
迭代器基础 | 掌握 iter() 和 next() |
实战练习 | 提升数据处理与简洁表达能力 |