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

  • 参数解包与实战技巧

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

相关推荐
ghost14325 分钟前
C#学习第17天:序列化和反序列化
开发语言·学习·c#
難釋懷1 小时前
bash的特性-bash中的引号
开发语言·chrome·bash
Hello eveybody2 小时前
C++按位与(&)、按位或(|)和按位异或(^)
开发语言·c++
6v6-博客2 小时前
2024年网站开发语言选择指南:PHP/Java/Node.js/Python如何选型?
java·开发语言·php
Baoing_2 小时前
Next.js项目生成sitemap.xml站点地图
xml·开发语言·javascript
被AI抢饭碗的人2 小时前
c++:c++中的输入输出(二)
开发语言·c++
lqqjuly2 小时前
C++ 面向对象关键语法详解:override、虚函数、转发调用和数组引用传参-策略模式
开发语言·c++
CPPAlien2 小时前
Python for MLOps - 第一阶段学习笔记
python
喵~来学编程啦2 小时前
【模块化编程】Python文件路径检查、跳转模块
开发语言·python
only-lucky2 小时前
QT日历控件重写美化
开发语言·qt