operator模块将Python操作符封装为函数,便于在高阶函数中使用。1. 算术运算如add、sub对应+、-;2. 比较运算如eq、lt对应==、
在Python中,operator 模块提供了对常见算术、比较、逻辑等操作的函数化支持。它把像 +、-、== 这样的操作符封装成了函数,方便在高阶函数(如 map()、filter()、sorted())中使用。
operator 模块中的函数大致可分为以下几类:
1. 算术运算
将基本数学操作转换为函数形式:
operator.add(a, b) → a + b
operator.sub(a, b) → a - b
operator.mul(a, b) → a * b
operator.truediv(a, b) → a / b
operator.floordiv(a, b) → a // b
operator.mod(a, b) → a % b
operator.pow(a, b) → a ** b
2. 比较运算
用于替代比较操作符,返回布尔值:
operator.eq(a, b) → a == b
operator.ne(a, b) → a != b
operator.lt(a, b) → a
operator.le(a, b) → a
operator.gt(a, b) → a > b
operator.ge(a, b) → a >= b
operator.is_(a, b) → a is b
operator.is_not(a, b) → a is not b
3. 逻辑与位运算
处理布尔和位级操作:
operator.and_(a, b) → a & b(按位与)operator.or_(a, b) → a | b(按位或)operator.xor(a, b) → a ^ b(异或)operator.not_(a) → not a
operator.invert(a) → ~a
4. 序列操作
用于列表、元组、字符串等序列类型:
operator.concat(a, b) → a + b(拼接)operator.contains(a, b) → b in a
operator.itemgetter(index) → 获取指定索引的元素operator.setitem(obj, index, value) → 设置元素operator.delitem(obj, index) → 删除元素下面是一些典型使用场景:
用 itemgetter 排序字典列表
import operatordata = [ {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20} ]
sorted_data = sorted(data, key=operator.itemgetter('age'))
按 age 升序排列
用 attrgetter 处理对象属性
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
people = [Person('Alice', 25), Person('Bob', 30)]
sorted_people = sorted(people, key=operator.attrgetter('age'))
用 methodcaller 调用对象方法
texts = [' hello ', ' world ', ' python ']
stripped = list(map(operator.methodcaller('strip'), texts))
# 结果: ['hello', 'world', 'python']
perator 模块?相比 lambda 函数,operator 提供了更清晰、高效且可读性更强的方式:
lambda x: x['key'],改用 itemgetter('key')
map、filter、reduce 配合使用基本上就这些。operator 模块虽小,但在数据处理和函数式编程中非常实用。掌握它能让代码更简洁专业。不复杂但容易忽略。