在Python编程中,我们经常需要执行各种运算操作,比如加法、比较、逻辑判断等。虽然可以直接使用 +、>、and 等符号,但在某些高级场景(如函数式编程、排序、高阶函数传参)中,将这些运算符作为函数对象传递会更加灵活和优雅。这时,Python标准库中的 operator 模块就派上用场了!
本文将带你从零开始,深入浅出地了解 Python operator模块 的核心功能,即使是编程小白也能轻松掌握。我们将涵盖常用函数、实际应用场景,并通过清晰的代码示例帮助你理解如何利用这个强大的工具提升代码质量。
operator 是 Python 内置的标准库模块,它将常见的运算符(如 +、-、== 等)封装成函数形式。这样你就可以像调用普通函数一样使用它们,特别适合用于 map()、filter()、sorted() 等高阶函数中。

下面是一些最常用的 operator 函数及其对应的运算符:
operator.add(a, b) → 相当于 a + boperator.sub(a, b) → 相当于 a - boperator.mul(a, b) → 相当于 a * boperator.eq(a, b) → 相当于 a == boperator.lt(a, b) → 相当于 a < boperator.gt(a, b) → 相当于 a > boperator.and_(a, b) → 相当于 a and b(注意下划线)假设我们要对一个数字列表求和,传统写法可能用循环或 sum()。但如果想用 functools.reduce,配合 operator.add 就非常简洁:
from functools import reduceimport operatornumbers = [1, 2, 3, 4, 5]total = reduce(operator.add, numbers)print(total) # 输出: 15相比写一个 lambda 表达式 lambda x, y: x + y,使用 operator.add 更清晰、性能也略优(因为是 C 实现)。
除了基本运算符,operator 模块还提供了两个极其实用的函数:itemgetter 和 attrgetter,常用于排序和数据提取。
当你有一个包含元组或字典的列表,想根据某个字段排序时,operator.itemgetter 非常方便。这是 operator.itemgetter用法 的经典场景:
import operatorstudents = [ ('Alice', 88), ('Bob', 92), ('Charlie', 75)]# 按成绩(索引1)降序排序sorted_students = sorted(students, key=operator.itemgetter(1), reverse=True)print(sorted_students)# 输出: [('Bob', 92), ('Alice', 88), ('Charlie', 75)]对于字典列表,也可以按 key 排序:
data = [ {'name': 'Alice', 'score': 88}, {'name': 'Bob', 'score': 92}]sorted_data = sorted(data, key=operator.itemgetter('score'))如果你处理的是自定义类的对象,可以用 attrgetter 按属性排序:
import operatorclass Student: def __init__(self, name, score): self.name = name self.score = score def __repr__(self): return f"Student('{self.name}', {self.score})"students_obj = [ Student('Alice', 88), Student('Bob', 92)]# 按 score 属性排序sorted_obj = sorted(students_obj, key=operator.attrgetter('score'))map、filter、reduce 等结合。通过本教程,你应该已经掌握了 Python运算符库 —— operator 模块的基本用法。无论是进行数学运算、逻辑比较,还是对复杂数据结构排序,operator 都能让你的代码更高效、更 Pythonic。
记住几个关键点:
add、mul、eq 等函数替代。itemgetter 和 attrgetter。operator 能显著提升代码质量。现在,就去你的项目中试试 Python内置运算符 的函数化用法吧!你会发现,小小的 operator 模块,竟能带来大大的便利。
本文由主机测评网于2025-12-09发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025125123.html