挑战14天学会Python,第8天学习笔记!加油!
一、概述
在 Python 中,函数不仅是可调用对象,更是“第一类公民”:
- 可作为参数传递
- 可作为返回值
- 可赋值给变量 本笔记围绕 函数类型、高阶函数(
filter
、map
)和 匿名函数(lambda
)展开,展示如何利用这些特性编写简洁、高效的代码。
二、函数类型(First-Class Functions)
(一)定义
Python 函数属于 第一类对象,支持以下操作:
- 赋值给变量
- 作为参数传递
- 作为返回值
- 存入容器(列表、字典等)
(二)示例
def greet(name):
return f"Hello, {name}!"
# 1. 赋值给变量
say_hi = greet
print(say_hi("Alice")) # Hello, Alice!
# 2. 存入列表
funcs = [greet, len, sum]
print(funcs[0]("Bob")) # Hello, Bob!
# 3. 作为参数传递
def apply(func, value):
return func(value)
print(apply(greet, "Charlie")) # Hello, Charlie!
三、过滤函数 filter
(一)定义
filter(function, iterable)
返回一个迭代器,仅保留使 function
返回 True
的元素,比如function
提供过滤的规则;iterable
为可迭代对象,如容器等元素。
(二)示例
# 过滤非空字符串
words = ["", "Python", "", "Code"]
non_empty = filter(None, words) # None 直接判断真假
print(list(non_empty)) # ['Python', 'Code']
# 提供过滤条件函数
def f(x1):
return x>50 # 找出大于50元素
data1 = [66, 15, 91, 28, 98, 50, 7, 80, 99]
filtered = filter(f1, data1)
data2 = list(filtered) #转换为列表
print (data2)
(三)注意事项
- 返回的是 惰性迭代器,需用
list()
显式转换。 - 函数参数可以是普通函数或
lambda
。
四、映射函数 map
(一)定义
map(function, iterable, ...)
将 function
应用于每个元素,返回结果的迭代器。
(二)示例
numbers = [1, 2, 3, 4, 5]
# 平方
squares = map(lambda x: x ** 2, numbers)
print(list(squares)) # [1, 4, 9, 16, 25]
# 多参数映射
a = [1, 2, 3]
b = [10, 20, 30]
sums = map(lambda x, y: x + y, a, b)
print(list(sums)) # [11, 22, 33]
(三)注意事项
- 输入的多个迭代器长度不同时,
map
以最短为准。 - 与
filter
一样,返回的是迭代器。
五、匿名函数 lambda
(一)定义
lambda
用于创建单行匿名函数,lambda关键字定义的函数被称为lambda函数,尤其是用在只需要使用一次的函数时,减少命名与调用步骤。语法简洁:
lambda 参数1, 参数2, ... : 表达式
(二)示例
# 普通函数
def add(x, y):
return x + y
# 等价的 lambda
add_lambda = lambda x, y: x + y
print(add_lambda(3, 4)) # 7
# 在 filter/map 中使用
numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers))
squares = list(map(lambda x: x ** 2, numbers))
print(evens) # [2, 4]
print(squares) # [1, 4, 9, 16, 25]
(三)注意事项
- lambda仅限单行表达式,不能包含多行语句或复杂逻辑。
- 可读性优先:复杂逻辑建议使用
def
定义具名函数。
六、综合应用案例
(一)数据清洗管道
data = [" Python ", " Java ", None, " C++ "]
# 步骤:过滤空值 → 去除空格 → 转大写
cleaned = map(
lambda s: s.strip().upper(),
filter(None, data)
)
print(list(cleaned)) # ['PYTHON', 'JAVA', 'C++']
(二)函数工厂
def power_factory(n):
return lambda x: x ** n
square = power_factory(2)
cube = power_factory(3)
print(square(3)) # 9
print(cube(3)) # 27
七、注意事项与最佳实践
-
可读性优先:复杂逻辑避免过度使用
lambda
。 -
惰性求值:
filter
和map
返回迭代器,大列表处理时节省内存。 -
替代方案:列表推导式通常比
map
+lambda
更直观:squares = [x**2 for x in numbers] # 推荐
八、总结
通过本笔记,我们掌握了:
- 函数作为第一类对象的灵活应用。
- 高阶函数
filter
和map
的使用场景与技巧。 lambda
匿名函数的简洁语法与限制。- 综合案例展示了函数式编程在数据处理中的强大能力。
这些工具将帮助你编写更简洁、更 Pythonic 的代码。后续我们将探索装饰器、生成器等高级函数特性。