当前位置: 首页 > news >正文

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)

性能考虑

  1. 在Python 2中,这些函数返回列表;在Python 3中返回迭代器,更节省内存
  2. 对于简单操作,列表推导式通常比map/filter更快
  3. 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函数式编程的重要组成部分,理解它们可以帮助你写出更简洁、更表达性的代码。

http://www.lryc.cn/news/617676.html

相关文章:

  • 【软考架构】主流数据持久化技术框架
  • Spring Boot Excel数据导入数据库实现详解
  • 6s081实验1
  • 机器翻译:一文掌握序列到序列(Seq2Seq)模型(包括手写Seq2Seq模型)
  • 机器学习TF-IDF算法详解
  • GPT-oss:OpenAI再次开源新模型,技术报告解读
  • 视频播放器哪个好用?视频播放器PotPlayer,KMP Player
  • FPGA学习笔记——DS18B20(数字温度传感器)
  • Mysql系列--6、内置函数
  • C++的结构体传参
  • 深度学习与遥感入门(五)|GAT 构图消融 + 分块全图预测:更稳更快的高光谱图分类(PyTorch Geometric 实战)
  • rust编译过程的中间表现形式如何查看,ast,hir,mir
  • Rust 实战五 | 配置 Tauri 应用图标及解决 exe 被识别为威胁的问题
  • istio如何采集method、url指标
  • Rust:anyhow 高效错误处理库核心用法详解
  • Elasticsearch 官方 Node.js 从零到生产
  • 用 Node.js 玩转 Elasticsearch从安装到增删改查
  • 基于动态顺序表实现【通讯录系统】:有文件操作部分哦!
  • 用 Docker 安装并启动 Redis:从入门到实战
  • Spring AI赋能图像识别:大数据模型驱动下的智能化变革
  • Webpack Loader 完全指南:从原理到配置的深度解析
  • 关于JavaScript 性能优化的实战指南
  • MySQL的索引(索引的数据结构-B+树索引):
  • Godot ------ 平滑拖动01
  • vue3中的子组件向父组件通信和父组件向子组件通信
  • 对抗样本攻击检测与防御
  • STM32 ESP8266 WiFi模块驱动
  • JVM管理数据的方式
  • CV 医学影像分类、分割、目标检测,之分类项目拆解
  • 【Lua】题目小练10