CodeWalk

map、filter、reduce 的用法

作者:屠龙少年 · 2026-05-30 12:55

Python 中 map()filter()reduce() 的用法和区别是什么?请用代码示例说明。

回答

屠龙少年

  • map(func, iterable):对每个元素应用函数,返回迭代器
  • filter(func, iterable):筛选使函数为 True 的元素,返回迭代器
  • reduce(func, iterable):累积计算,需要 functools.reduce
from functools import reduce

nums = [1, 2, 3, 4, 5]
list(map(lambda x: x*2, nums))      # [2, 4, 6, 8, 10]
list(filter(lambda x: x%2==0, nums)) # [2, 4]
reduce(lambda a, b: a*b, nums)      # 120

在 Python 3 中,map/filter 返回迭代器(惰性求值),reduce 被移到了 functools。通常推荐用列表推导式和生成器表达式替代它们,更 Pythonic。