Python 高阶函数:filter、map、reduce 详解
Python 高阶函数:filter、map、reduce 详解
Python 提供了几个内置的高阶函数,用于对可迭代对象进行函数式编程风格的操作。其中最常用的三个是 filter()
、map()
和 reduce()
。
1. filter() 函数
filter()
函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象。
语法
filter(function, iterable)
功能
- 对
iterable
中的每个元素应用function
- 只保留使
function
返回True
的元素
示例
# 过滤出偶数
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # 输出: [2, 4, 6]# 过滤掉空字符串
words = ["hello", "", "world", " ", "python"]
non_empty = filter(None, words) # 当function为None时,自动过滤掉bool值为False的元素
print(list(non_empty)) # 输出: ['hello', 'world', ' ', 'python']# 更精确的过滤空字符串和空格
non_empty = filter(lambda x: x.strip(), words)
print(list(non_empty)) # 输出: ['hello', 'world', 'python']
2. map() 函数
map()
函数将指定函数应用于可迭代对象的每个元素,返回一个迭代器。
语法
map(function, iterable, ...)
功能
- 对
iterable
中的每个元素应用function
- 可以接受多个可迭代对象(函数需要相应数量的参数)
示例
# 对每个元素求平方
numbers = [1, 2, 3, 4]
squares = map(lambda x: x**2, numbers)
print(list(squares)) # 输出: [1, 4, 9, 16]# 多个可迭代对象
nums1 = [1, 2, 3]
nums2 = [4, 5, 6]
sums = map(lambda x, y: x + y, nums1, nums2)
print(list(sums)) # 输出: [5, 7, 9]# 使用内置函数
words = ["hello", "world"]
lengths = map(len, words)
print(list(lengths)) # 输出: [5, 5]
3. reduce() 函数
reduce()
函数(在 Python 3 中位于 functools
模块)对序列中的元素进行累积操作。
语法
from functools import reduce
reduce(function, iterable[, initializer])
功能
- 对
iterable
中的元素两两累积应用function
function
必须接受两个参数- 如果有
initializer
,则作为第一个累积的初始值
示例
from functools import reduce# 计算列表元素的乘积
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 输出: 24# 计算阶乘
n = 5
factorial = reduce(lambda x, y: x * y, range(1, n+1))
print(factorical) # 输出: 120# 使用初始值
numbers = [1, 2, 3]
sum_with_initial = reduce(lambda x, y: x + y, numbers, 10)
print(sum_with_initial) # 输出: 16 (10 + 1 + 2 + 3)# 连接字符串
words = ["Python", "is", "awesome"]
sentence = reduce(lambda x, y: f"{x} {y}", words)
print(sentence) # 输出: "Python is awesome"
比较与选择
函数 | 返回值 | 用途 | 替代方案(推荐) |
---|---|---|---|
filter() | 过滤后的迭代器 | 选择满足条件的元素 | 列表推导式 + if 条件 |
map() | 转换后的迭代器 | 对每个元素应用函数进行转换 | 列表推导式 |
reduce() | 单一累积结果 | 将序列缩减为单一累积值 | 显式循环或专用函数(sum等) |
现代Python替代方案
虽然这些函数很有用,但在许多情况下,列表推导式和生成器表达式更受推荐:
# filter 的替代
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [x for x in numbers if x % 2 == 0]# map 的替代
squares = [x**2 for x in numbers]# reduce 的替代(求和)
total = sum(numbers)
性能考虑
- 在Python 2中,这些函数返回列表;在Python 3中返回迭代器,更节省内存
- 对于简单操作,列表推导式通常比
map
/filter
更快 reduce
通常可以用更明确的循环或专用函数(如sum()
、math.prod()
)替代,这样代码更易读
实际应用示例
数据处理管道
from functools import reducedata = ["10", "20", "30", "40", "abc", "50"]# 过滤非数字字符串 -> 转换为整数 -> 求和
result = reduce(lambda x, y: x + y,map(int, filter(str.isdigit, data)),0
)
print(result) # 输出: 150 (10+20+30+40+50)
多步骤转换
# 将字符串列表转换为大写,过滤短词,然后连接
words = ["python", "is", "an", "awesome", "language"]result = reduce(lambda x, y: f"{x} {y}",filter(lambda x: len(x) > 2, map(str.upper, words))
)
print(result) # 输出: "PYTHON IS AWESOME LANGUAGE"
这些高阶函数是Python函数式编程的重要组成部分,理解它们可以帮助你写出更简洁、更表达性的代码。