Python 高阶函数
高阶函数接受函数作为参数或返回函数,是函数式编程的基础工具。
map 函数
对序列每个元素应用函数,返回迭代器。
Python
# 基本用法
numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x ** 2, numbers)
print(list(squared)) # [1, 4, 9, 16, 25]
# 使用内置函数
words = ['hello', 'world']
upper = map(str.upper, words)
print(list(upper)) # ['HELLO', 'WORLD']
# 多序列处理
a = [1, 2, 3]
b = [4, 5, 6]
sums = map(lambda x, y: x + y, a, b)
print(list(sums)) # [5, 7, 9]
filter 函数
过滤序列中满足条件的元素,返回迭代器。
Python
# 基本用法
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # [2, 4, 6, 8, 10]
# 过滤 None 值
values = [1, None, 2, None, 3]
valid = filter(None, values)
print(list(valid)) # [1, 2, 3]
# 过滤字符串
words = ['', 'hello', '', 'world', 'python']
non_empty = filter(bool, words)
print(list(non_empty)) # ['hello', 'world', 'python']
reduce 函数
累积处理序列元素,返回单一结果。需从 functools 导入。
Python
from functools import reduce
# 求和
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total) # 15
# 求乘积
product = reduce(lambda x, y: x * y, numbers)
print(product) # 120
# 指定初始值
total = reduce(lambda x, y: x + y, numbers, 100)
print(total) # 115
# 找最大值
max_val = reduce(lambda x, y: x if x > y else y, numbers)
print(max_val) # 5
链式调用
Python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 先过滤再映射
result = map(lambda x: x ** 2, filter(lambda x: x % 2 == 0, numbers))
print(list(result)) # [4, 16, 36, 64, 100]
# 使用生成器表达式更清晰
result = (x ** 2 for x in numbers if x % 2 == 0)
print(list(result)) # [4, 16, 36, 64, 100]
函数对比
| 函数 | 功能 | 返回类型 |
|---|---|---|
| map | 映射变换 | 迭代器 |
| filter | 过滤筛选 | 迭代器 |
| reduce | 累积归约 | 单一值 |
性能对比
Python
import timeit
# map vs 列表推导式
numbers = range(1000)
# map 方式
timeit.timeit('list(map(lambda x: x**2, numbers))',
globals=globals(), number=1000)
# 列表推导式
timeit.timeit('[x**2 for x in numbers]',
globals=globals(), number=1000)
列表推导式通常比 map 更快,但 map 在处理已定义函数时更优。
实用示例
Python
# 字符串处理
sentences = ['Hello World', 'Python Programming']
words = map(str.split, sentences)
print(list(words)) # [['Hello', 'World'], ['Python', 'Programming']]
# 数据转换
data = [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
names = map(lambda x: x[0], data)
ages = map(lambda x: x[1], data)
print(list(names)) # ['Alice', 'Bob', 'Charlie']
print(list(ages)) # [25, 30, 35]
# 类型转换
strings = ['1', '2', '3', '4', '5']
ints = map(int, strings)
print(list(ints)) # [1, 2, 3, 4, 5]
要点总结
map(func, seq)对每个元素应用函数filter(func, seq)保留满足条件的元素reduce(func, seq)累积处理返回单一值- 三个函数都返回迭代器(reduce除外)
- 链式调用时注意性能,生成器表达式可能更清晰
- 配合 lambda 可快速实现数据处理
📝 发现内容有误?点击此处直接编辑