全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-19 8 分钟 ✍️ juanwangdev

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 可快速实现数据处理

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python 闭包函数
下一篇 → Python itertools 模块
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库