Python的operator模块提供了一系列函数,对应Python内置的各种运算符。这些函数让运算符操作更加直观,特别适合在函数式编程中使用。
在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)) # Falseoperator模块可以用于获取和设置对象的元素:
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 = 26operator模块在排序时特别有用:
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的运算符以函数形式呈现,这在很多场景下非常有用:
函数式编程:配合map、filter、reduce等函数使用
动态操作:根据运行时的条件选择不同的运算
代码清晰:让运算符操作更加明确和可读
排序操作:为复杂数据结构的排序提供便利
掌握operator模块能够让你的Python代码更加灵活和强大。对于初学者来说,可以从比较运算和数学运算开始练习,逐步掌握更高级的用法。
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!