上一期小练习解答(第7期回顾)
✅ 练习1:找出1~100中能被3或5整除的数
result = [x for x in range(1, 101) if x % 3 == 0 or x % 5 == 0]
✅ 练习2:生成字符串长度字典
words = ["apple", "banana", "grape"]
lengths = {word: len(word) for word in words}
✅ 练习3:乘法字典
multiplication_table = {(i, j): i * j for i in range(1, 6) for j in range(1, 6)}
✅ 练习4:唯一偶数集合
lst = [1, 2, 2, 3, 4, 4, 6]
even_set = {x for x in lst if x % 2 == 0}
本期主题:Lambda函数与高阶函数
🟦 8.1 匿名函数 lambda
匿名函数(Lambda)是用来创建简单函数的一种简洁方式。
✅ 基本语法:
lambda 参数: 表达式
⚠️ 注意:lambda
函数只能写一行表达式,不能有多行语句。
示例:普通函数 vs lambda
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() 函数
对可迭代对象中的每个元素执行某个函数。
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
print(squares) # [1, 4, 9, 16]
8.4 filter() 函数
筛选符合条件的元素。
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)
对所有元素累积运算。
from functools import reduce
nums = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, nums)
print(total) # 10
应用实例:常见用法组合
🔹 对字符串列表大小写转换
words = ["apple", "banana", "grape"]
upper = list(map(lambda w: w.upper(), words))
🔹 保留长度大于5的字符串
long_words = list(filter(lambda w: len(w) > 5, words))
🔹 所有价格加税10%
prices = [100, 200, 300]
taxed = list(map(lambda p: round(p * 1.1, 2), prices))
本期小练习
-
使用
map
将[1, 2, 3, 4, 5]
转为字符串列表。 -
使用
filter
从列表中筛选出所有回文字符串(例如"madam"
)。 -
使用
reduce
计算[2, 3, 4]
的乘积。 -
定义一个
lambda
函数,实现 x² + 2x + 1 的计算。
本期小结
-
学习了 lambda匿名函数 的用法。
-
掌握了三种常用的高阶函数:map, filter, reduce。
-
初步感受了 函数式编程思想 的强大与简洁。
第9期预告:
下一期我们将深入了解:
-
Python中的函数定义进阶
-
可变参数:
*args
与**kwargs
-
参数解包与实战技巧
-
默认参数 & 关键字参数的使用场景