Python语法系列博客 · 第8期[特殊字符] Lambda函数与高阶函数:函数式编程初体验

上一期小练习解答(第7期回顾)

✅ 练习1:找出1~100中能被3或5整除的数
python 复制代码
result = [x for x in range(1, 101) if x % 3 == 0 or x % 5 == 0]

✅ 练习2:生成字符串长度字典

python 复制代码
words = ["apple", "banana", "grape"]
lengths = {word: len(word) for word in words}

✅ 练习3:乘法字典

python 复制代码
multiplication_table = {(i, j): i * j for i in range(1, 6) for j in range(1, 6)}

✅ 练习4:唯一偶数集合

python 复制代码
lst = [1, 2, 2, 3, 4, 4, 6]
even_set = {x for x in lst if x % 2 == 0}

本期主题:Lambda函数与高阶函数


🟦 8.1 匿名函数 lambda

匿名函数(Lambda)是用来创建简单函数的一种简洁方式。

✅ 基本语法:
python 复制代码
lambda 参数: 表达式

⚠️ 注意:lambda 函数只能写一行表达式,不能有多行语句。

示例:普通函数 vs lambda

python 复制代码
def add(x, y):
    return x + y

add_lambda = lambda x, y: x + y

print(add(2, 3))         # 5
print(add_lambda(2, 3))  # 5

8.2 高阶函数简介

高阶函数指的是接收函数作为参数 ,或返回另一个函数的函数。

8.3 map() 函数

对可迭代对象中的每个元素执行某个函数。

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

8.4 filter() 函数

筛选符合条件的元素。

python 复制代码
nums = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens)  # [2, 4, 6]

8.5 reduce() 函数(需导入 functools)

对所有元素累积运算。

python 复制代码
from functools import reduce

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

应用实例:常见用法组合

🔹 对字符串列表大小写转换
python 复制代码
words = ["apple", "banana", "grape"]
upper = list(map(lambda w: w.upper(), words))

🔹 保留长度大于5的字符串

python 复制代码
long_words = list(filter(lambda w: len(w) > 5, words))

🔹 所有价格加税10%

python 复制代码
prices = [100, 200, 300]
taxed = list(map(lambda p: round(p * 1.1, 2), prices))

本期小练习

  1. 使用 map[1, 2, 3, 4, 5] 转为字符串列表。

  2. 使用 filter 从列表中筛选出所有回文字符串(例如 "madam")。

  3. 使用 reduce 计算 [2, 3, 4] 的乘积。

  4. 定义一个 lambda 函数,实现 x² + 2x + 1 的计算。

本期小结

  • 学习了 lambda匿名函数 的用法。

  • 掌握了三种常用的高阶函数:map, filter, reduce

  • 初步感受了 函数式编程思想 的强大与简洁。

第9期预告:

下一期我们将深入了解:

  • Python中的函数定义进阶

  • 可变参数:*args**kwargs

  • 参数解包与实战技巧

  • 默认参数 & 关键字参数的使用场景

相关推荐
Cloud_Shy6189 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 33 - 35)
开发语言·人工智能·笔记·python·学习方法
星恒随风9 小时前
C++ 类和对象入门(五):初始化列表、explicit 和 static 成员详解
开发语言·c++·笔记·学习·状态模式
艾利克斯冰9 小时前
Java 设计模式-行为型模式(更新中)
java·开发语言·设计模式
倒霉蛋小马9 小时前
Java新特性:record关键字
java·开发语言
abcy0712139 小时前
python pandas csv异步后台清洗前端优先返回成功信息
前端·python·pandas
budingxiaomoli10 小时前
Spring日志
java·开发语言
牛油果子哥q10 小时前
【C++ STL vector】C++ STL vector 终极精讲:动态数组底层原理、两倍扩容机制、迭代器失效、增删查改、性能剖析与工程避坑指南
开发语言·c++
颜酱10 小时前
LangChain使用RAG 入门:让大模型读懂你的私有文档
python·langchain
贩卖黄昏的熊10 小时前
flex 布局快速梳理
开发语言·javascript·css3·html5
天天进步201510 小时前
Python全栈项目--校园智能宿舍管理系统
开发语言·python