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

  • 参数解包与实战技巧

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

相关推荐
XiaoMu_00129 分钟前
基于Django+Vue3+YOLO的智能气象检测系统
python·yolo·django
honder试试1 小时前
焊接自动化测试平台图像处理分析-模型训练推理
开发语言·python
^Rocky2 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
心本无晴.2 小时前
Python进程,线程
python·进程
ponnylv2 小时前
深入剖析Spring Boot启动流程
java·开发语言·spring boot·spring
萧邀人2 小时前
第一课、Cocos Creator 3.8 安装与配置
开发语言
Jayden_Ruan3 小时前
C++逆向输出一个字符串(三)
开发语言·c++·算法
不吃鱼的羊3 小时前
启动文件Startup_vle.c
c语言·开发语言
VBA63373 小时前
VBA之Word应用第四章第二节:段落集合Paragraphs对象(二)
开发语言
点云SLAM4 小时前
C++ 常见面试题汇总
java·开发语言·c++·算法·面试·内存管理