6个月Python学习计划 Day 15 - 函数式编程、高阶函数、生成器/迭代器

第三周 Day 1

🎯 今日目标

  • 掌握 Python 中函数式编程的核心概念
  • 熟悉 map()、filter()、reduce() 等高阶函数
  • 结合 lambda 和 列表/字典 进行数据处理练习
  • 了解生成器与迭代器基础,初步掌握惰性计算概念

🧠 函数式编程基础

函数式编程是一种"将函数作为数据处理工具"的风格,强调表达式、不可变性和链式操作。

🛠 常用高阶函数

1️⃣ map(func, iterable):将函数应用于序列的每个元素

python 复制代码
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
print(squares)  # 输出 [1, 4, 9, 16]

2️⃣ filter(func, iterable):过滤序列中符合条件的元素

python 复制代码
nums = [5, 8, 12, 3, 7]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)  # 输出 [8, 12]

reduce(func, iterable):连续两两执行函数(需导入)

python 复制代码
from functools import reduce

nums = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, nums)
print(total)  # 输出 10

🔁 生成器 Generator

生成器是一种惰性迭代器,只在需要时计算结果,节省内存。

python 复制代码
def countdown(n):
    while n > 0:
        yield n
        n -= 1

for i in countdown(5):
    print(i)

🔄 迭代器 Iterator

任何实现了 iter () 和 next() 方法的对象都可以被称为迭代器。

python 复制代码
lst = iter([1, 2, 3])
print(next(lst))  # 输出 1
print(next(lst))  # 输出 2

🧪 今日练习任务

✅ 练习1:用 map 和 lambda 对列表每个数平方

python 复制代码
nums = [2, 4, 6, 8]
result = list(map(lambda x: x**2, nums))
print(result)

✅ 练习2:用 filter 筛选出长度大于3的字符串

python 复制代码
words = ['hi', 'hello', 'python', 'no']
filtered = list(filter(lambda w: len(w) > 3, words))
print(filtered)

✅ 练习3:实现一个生成器,生成前 N 个偶数

python 复制代码
def even_gen(n):
    for i in range(n):
        yield i * 2

print(list(even_gen(5)))  # 输出 [0, 2, 4, 6, 8]

📌 今日总结

内容 说明
函数式编程入门 高阶函数 map/filter/reduce
惰性计算 生成器节省内存,适合大数据处理
迭代器基础 掌握 iter() 和 next()
实战练习 提升数据处理与简洁表达能力
相关推荐
IVEN_2 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang3 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮3 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling3 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮6 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽7 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健1 天前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞1 天前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers