Python3入门指南Python语言的特点和实际应用Python3环境搭建配置VSCode进行Python开发Python基础语法Python变量与数据类型Python数据类型转换Python解释器使用Python注释使用Python运算符Python数字类型Python字符串操作Python列表操作Python元组使用Python字典使用Python集合使用Python条件控制详解Python循环语句详解Python编程入门实践Python推导式详解Python迭代器和生成器Python with语句详解Python函数详解Python lambda(匿名函数)Python装饰器Python数据结构Python模块和包使用Python中__name__和__main__的用法Python输入输出:从基础到文件操作Python文件操作Python OS模块使用Python错误和异常处理Python面向对象编程Python命名空间和作用域Python虚拟环境:venv详细教程Python类型注解Python标准库常用模块Python正则表达式Python CGI编程Python MySQL(mysql-connector驱动)Python MySQL(PyMySQL驱动)Python网络编程Python发送邮件Python多线程编程Python XML解析Python JSON解析Python日期和时间处理Python操作MongoDBPython urllib库使用Python uWSGI 安装与配置Python pip包管理工具Python operator模块Python math模块Python requests模块HTTP请求Python random模块Python OpenAI库Python AI绘画制作Python statistics模块Python hashlib模块:哈希加密Python量化交易Python pyecharts数据可视化Python Selenium网页自动化Python BeautifulSoup网页数据提取Python Scrapy爬虫框架Python Markdown转HTMLPython sys模块Python Pickle模块:数据存储Python subprocess模块Python queue队列模块Python StringIO内存文件操作Python logging日志记录Python datetime日期时间处理Python re正则表达式Python csv表格数据处理Python threading 多线程编程Python asyncio 异步编程Python PyQt 图形界面开发Python 应用方向和常用库框架

Python operator模块

Python的operator模块提供了一系列函数,对应Python内置的各种运算符。这些函数让运算符操作更加直观,特别适合在函数式编程中使用。


operator模块的作用

在Python 2版本中,有一个cmp()函数用来比较两个对象的大小。但Python 3移除了这个函数。operator模块提供了更清晰的比较方法,让我们能够用函数的形式进行各种运算操作。


比较运算函数

operator模块包含所有常见的比较运算函数:

import operator

# 数字比较示例
x = 15
y = 25

print("x =", x, ", y =", y)
print("x < y:", operator.lt(x, y))   # 小于
print("x <= y:", operator.le(x, y))  # 小于等于
print("x == y:", operator.eq(x, y))  # 等于
print("x != y:", operator.ne(x, y))  # 不等于
print("x > y:", operator.gt(x, y))   # 大于
print("x >= y:", operator.ge(x, y))  # 大于等于

输出结果:

x = 15 , y = 25
x < y: True
x <= y: True
x == y: False
x != y: True
x > y: False
x >= y: False

字符串也可以比较:

import operator

str1 = "apple"
str2 = "banana"

print("字符串比较:")
print("apple < banana:", operator.lt(str1, str2))
print("apple == apple:", operator.eq(str1, "apple"))

列表比较示例:

import operator

list1 = [1, 2, 3]
list2 = [1, 2, 4]
list3 = [1, 2, 3]

print("列表比较:")
print("list1 == list2:", operator.eq(list1, list2))
print("list1 == list3:", operator.eq(list1, list3))
print("list1 < list2:", operator.lt(list1, list2))


数学运算函数

operator模块提供了各种数学运算函数:

import operator

a = 10
b = 3

print("基本数学运算:")
print("加法:", operator.add(a, b))        # 10 + 3 = 13
print("减法:", operator.sub(a, b))        # 10 - 3 = 7
print("乘法:", operator.mul(a, b))        # 10 * 3 = 30
print("除法:", operator.truediv(a, b))    # 10 / 3 ≈ 3.333
print("整除:", operator.floordiv(a, b))   # 10 // 3 = 3
print("取模:", operator.mod(a, b))        # 10 % 3 = 1
print("幂运算:", operator.pow(a, b))      # 10 ** 3 = 1000


位运算函数

对于二进制操作,operator模块也提供了相应函数:

import operator

x = 10  # 二进制: 1010
y = 4   # 二进制: 0100

print("位运算:")
print("按位与:", operator.and_(x, y))   # 1010 & 0100 = 0000 (0)
print("按位或:", operator.or_(x, y))    # 1010 | 0100 = 1110 (14)
print("按位异或:", operator.xor(x, y))  # 1010 ^ 0100 = 1110 (14)
print("左移位:", operator.lshift(x, 1)) # 1010 << 1 = 10100 (20)
print("右移位:", operator.rshift(x, 1)) # 1010 >> 1 = 0101 (5)
print("按位取反:", operator.invert(x))  # ~1010 = ... (取决于整数位数)


序列操作函数

operator模块对列表、字符串等序列类型也提供了操作函数:

import operator

# 序列操作
list1 = [1, 2, 3]
list2 = [4, 5, 6]

print("序列操作:")
print("列表拼接:", operator.concat(list1, list2))  # [1,2,3,4,5,6]

text = "hello"
print("字符串重复:", operator.mul(text, 3))  # "hellohellohello"

# 包含测试
numbers = [1, 2, 3, 4, 5]
print("3在列表中:", operator.contains(numbers, 3))  # True
print("6在列表中:", operator.contains(numbers, 6))  # False


项目获取和设置

operator模块可以用于获取和设置对象的元素:

import operator

my_list = [10, 20, 30, 40, 50]
my_dict = {'name': 'John', 'age': 30}

print("元素访问:")
print("列表第三个元素:", operator.getitem(my_list, 2))  # 30
print("字典name键:", operator.getitem(my_dict, 'name'))  # John

# 设置元素
operator.setitem(my_list, 0, 100)
print("修改后的列表:", my_list)  # [100, 20, 30, 40, 50]

operator.setitem(my_dict, 'age', 31)
print("修改后的字典:", my_dict)  # {'name': 'John', 'age': 31}

# 删除元素
operator.delitem(my_list, 1)
print("删除后的列表:", my_list)  # [100, 30, 40, 50]


切片操作

operator模块支持Python的切片操作:

import operator

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print("切片操作:")
# 获取切片
slice_obj = slice(2, 7, 2)
print("切片[2:7:2]:", operator.getitem(numbers, slice_obj))  # [2, 4, 6]

# 设置切片
operator.setitem(numbers, slice(0, 3), [10, 11, 12])
print("设置切片后的列表:", numbers)  # [10, 11, 12, 3, 4, 5, 6, 7, 8, 9]

# 删除切片
operator.delitem(numbers, slice(5, 8))
print("删除切片后的列表:", numbers)  # [10, 11, 12, 3, 4, 9]


属性操作

operator模块还可以操作对象属性:

import operator

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

person = Person("Alice", 25)

print("属性操作:")
print("姓名:", operator.attrgetter('name')(person))  # Alice
print("年龄:", operator.attrgetter('age')(person))   # 25

# 设置属性
operator.attrgetter('age')(person)  # 这只是获取,不能直接设置
# 通常我们直接使用 person.age = 26


实际应用场景

在排序中使用

operator模块在排序时特别有用:

import operator

students = [
    {'name': 'John', 'score': 85},
    {'name': 'Alice', 'score': 92},
    {'name': 'Bob', 'score': 78}
]

# 按分数排序
students_sorted = sorted(students, key=operator.itemgetter('score'))
print("按分数排序:", students_sorted)

# 按姓名排序
students_sorted_by_name = sorted(students, key=operator.itemgetter('name'))
print("按姓名排序:", students_sorted_by_name)

在函数式编程中使用

import operator
from functools import reduce

numbers = [1, 2, 3, 4, 5]

# 计算乘积
product = reduce(operator.mul, numbers)
print("1到5的乘积:", product)  # 120

# 计算总和
total = reduce(operator.add, numbers)
print("1到5的总和:", total)  # 15

# 逻辑运算
values = [True, False, True]
all_true = all(values)
any_true = any(values)
print("所有值为真:", all_true)
print("任一值为真:", any_true)

动态操作选择

import operator

def calculate(operation, a, b):
    operations = {
        'add': operator.add,
        'subtract': operator.sub,
        'multiply': operator.mul,
        'divide': operator.truediv
    }
    
    if operation in operations:
        return operations[operation](a, b)
    else:
        return None

print("动态运算示例:")
print("10 + 5 =", calculate('add', 10, 5))
print("10 - 5 =", calculate('subtract', 10, 5))
print("10 * 5 =", calculate('multiply', 10, 5))
print("10 / 5 =", calculate('divide', 10, 5))


方法命名规则

operator模块中的函数有两种命名方式:

  • 常规形式:add(), sub(), mul()

  • 双下划线形式:__add__(), __sub__(), __mul__()

两种形式功能完全相同,建议使用常规形式,代码更清晰。

import operator

# 两种方式效果相同
print("常规形式:", operator.add(5, 3))
print("双下划线形式:", operator.__add__(5, 3))


总结

运算

语法

函数

加法

a + b

add(a, b)

字符串拼接

seq1 + seq2

concat(seq1, seq2)

包含测试

obj in seq

contains(seq, obj)

除法

a / b

truediv(a, b)

除法

a // b

floordiv(a, b)

按位与

a & b

and_(a, b)

按位异或

a ^ b

xor(a, b)

按位取反

~ a

invert(a)

按位或

a | b

or_(a, b)

取幂

a ** b

pow(a, b)

标识

a is b

is_(a, b)

标识

a is not b

is_not(a, b)

索引赋值

obj[k] = v

setitem(obj, k, v)

索引删除

del obj[k]

delitem(obj, k)

索引取值

obj[k]

getitem(obj, k)

左移

a << b

lshift(a, b)

取模

a % b

mod(a, b)

乘法

a * b

mul(a, b)

矩阵乘法

a @ b

matmul(a, b)

取反(算术)

- a

neg(a)

取反(逻辑)

not a

not_(a)

正数

+ a

pos(a)

右移

a >> b

rshift(a, b)

切片赋值

seq[i:j] = values

setitem(seq, slice(i, j), values)

切片删除

del seq[i:j]

delitem(seq, slice(i, j))

切片取值

seq[i:j]

getitem(seq, slice(i, j))

字符串格式化

s % obj

mod(s, obj)

减法

a - b

sub(a, b)

真值测试

obj

truth(obj)

比较

a < b

lt(a, b)

比较

a <= b

le(a, b)

相等

a == b

eq(a, b)

不等

a != b

ne(a, b)

比较

a >= b

ge(a, b)

比较

a > b

gt(a, b)

operator模块让Python的运算符以函数形式呈现,这在很多场景下非常有用:

  1. 函数式编程:配合map、filter、reduce等函数使用

  2. 动态操作:根据运行时的条件选择不同的运算

  3. 代码清晰:让运算符操作更加明确和可读

  4. 排序操作:为复杂数据结构的排序提供便利

掌握operator模块能够让你的Python代码更加灵活和强大。对于初学者来说,可以从比较运算和数学运算开始练习,逐步掌握更高级的用法。

本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!

链接: https://fly63.com/course/36_2123

目录选择