文章开篇

Python的魅力,犹如星河璀璨,无尽无边;人生苦短、我用Python!


operator简介

operator 模块提供了一套与Python的内置运算符对应的高效率函数;
例如,add(3, 4)相当于3+4,许多函数名与特殊方法名相同,只是没有双下划线;
为了向后兼容性,也保留了许多包含双下划线的函数
为了代码的易读性,建议使用没有双下划线的函数;
函数包含的种类有:对象的比较运算、逻辑运算、数学运算以及序列运算;
初看起来,可能不明白为什么有人想要使用这些函数,因为它们执行的操作可通过常规语法轻松完成;
这些函数适合处理使用回调函数的代码的场景,以及如果不使用这些函数,就需要使用 lambda 定义匿名函数的情况。


比较运算

运算 函数 语法
小于 lt(a, b) a < b
小于等于 le(a, b) a <= b
大于 gt(a, b) a > b
大于等于 ge(a, b) a >= b
等于 eq(a, b) a == b
不等于 ne(a, b) a != b
import operator

print(operator.eq(10, 10))  # True(等于)
print(operator.ne(10, 15))  # True(不等于)
print(operator.gt(15, 10))  # True(大于)
print(operator.ge(15, 15))  # True(大于等于)
print(operator.lt(10, 15))  # True(小于)
print(operator.le(10, 10))  # True(小于等于)

# 双下划线版本和上述函数用法一致
# operator.__lt__(a, b)
# operator.__le__(a, b)
# operator.__eq__(a, b)
# operator.__ne__(a, b)
# operator.__ge__(a, b)
# operator.__gt__(a, b)

逻辑运算

运算 函数 语法
and_(a, b) a & b
or_(a, b) a
异或 xor(a, b) a ^ b
取反 invert(a) ~ a
对象是否相等 is_(a, b) a is b
对象是否不相等 is_not(a, b) a is not b
真值 truth(obj) obj
from operator import *

# 与
print(and_(0, 1))   # 0
print(and_(1, 1))   # 1

# 或
print(or_(0, 1))    # 1
print(or_(1, 1))    # 1

# 异或
print(xor(0, 1))    # 1
print(xor(1, 1))    # 0

# 取反
print(invert(True)) # -2
print(invert(1))    # -2
print(invert(2))    # -2
print(invert(-2))   # 1

# 对象是否相等
a = [1, 3, 5, 7, 9]
b = [1, 3, 5, 7, 9]
c = a
print(is_(a, b))    # False
print(is_(a, c))    # True

# 对象是否不相等
print(is_not(a, b)) # True
print(is_not(a, c)) # False

# 真值
print(truth(0)) # False
print(truth(1)) # True


数学运算

运算 函数 语法
add(a ,b) a + b
truediv(a, b) a / b
mul(a, b) a * b
sub(a, b) a - b
pow(a, b) a ** b
负数 neg(a) - a
正数 pos(a) + a
取模 mod(a, b) a % b

from operator import *

print(add(1, 2))    # 3
print(truediv(3, 2))# 1.5
print(mul(3, 2))    # 6
print(sub(3, 2))    # 1
print(pow(3, 2))    # 9
print(neg(3))       # -3
print(pos(3))       # 3
print(mod(3, 2))    # 1

序列运算

运算 函数 语法
字符串拼接 concat(seq1, seq2) seq1 + seq2
包含 contains(seq, obj) obj in seq
索引赋值 setitem(obj, i, v) obj[i] = v
索引删除 delitem(obj, i) del obj[i]
索引取值 getitem(obj, i) obj[i]
切片赋值 setitem(seq, slice(i, j), values) seq[i:j] = values
切片删除 delitem(seq, slice(i, j)) del seq[i:j]
切片取值 getitem(seq, slice(i, j)) seq[i:j]
格式化 mod(s, obj) s % obj
from operator import *

# 字符串拼接
print(concat('hello', ' world'))  # hello world
# 包含
print(contains("hello world", "e"))  # True

# 索引赋值
a = [1, 3, 5, 7, 9]
print(a)  # [1, 3, 5, 7, 9]
setitem(a, 0, 11)
print(a)  # [11, 3, 5, 7, 9]

# 索引删除
a = [1, 3, 5, 7, 9]
print(a)  # [1, 3, 5, 7, 9]
delitem(a, 1)
print(a)  # [1, 5, 7, 9]

# 索引取值
a = [1, 3, 5, 7, 9]
print(getitem(a, 1))  # 3

# 切片删除
a = [1, 3, 5, 7, 9]
print(a)  # [1, 3, 5, 7, 9]
delitem(a, slice(1, 3))
print(a)  # [1, 7, 9]

# 切片赋值
a = [1, 3, 5, 7, 9]
print(a)  # [1, 3, 5, 7, 9]
setitem(a, slice(1, 3), ['a', 'b', 'c'])
print(a)  # [1, 'a', 'b', 'c', 7, 9]

# 格式化
print(mod("我是 %s", "zhangsan"))   # 我是 zhangsan

attrgetter

operator 模块中的 attrgetter 是一个用于获取对象属性的高级工具。
它接受一个或多个属性名作为参数,并返回一个可调用对象;
当这个返回的对象被调用时,它会接收一个对象作为参数,并返回该对象的指定属性值。

示例代码
import operator
from operator import *


class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def __repr__(self):
        return '%s(name=%r,score=%r)' % (self.__class__.__name__, self.name, self.score)


if __name__ == '__main__':
    students = [Student("zhangSan", 89),
                Student("liSi", 60),
                Student("wangWu", 70),
                Student("xiaoMing", 100)]

    print("按照【分数】排序: ")
    print(sorted(students, key=attrgetter('score'), reverse=True))
    # [Student(name='xiaoMing',score=100), Student(name='zhangSan',score=89), Student(name='wangWu',score=70), Student(name='liSi',score=60)]
    g = attrgetter("score")  # 获取【分数】属性
    vals = [g(i) for i in students]
    print(f'获取分数属性:{vals}') # 获取分数属性:[89, 60, 70, 100]
    
    names = list(map(operator.attrgetter('name'), students))
    print(names) # ['zhangSan', 'liSi', 'wangWu', 'xiaoMing']

itemgetter

operator 模块中的 itemgetter 函数是一个非常实用的工具;
它允许你获取对象(如字典、列表、元组等)的某个或多个元素;
与 attrgetter 不同,itemgetter 是用来获取容器类型对象中的元素,而不是对象的属性。


1.从字典中提取数据
import operator

# 创建一个字典
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}

# 使用itemgetter提取'name'和'age'
getter = operator.itemgetter('name', 'age')
result = getter(person)

# 输出结果
print(result)  # 输出: ('Alice', 25)

2.作为字典排序的 key 函数

import operator

# 创建一个字典列表
people = [
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 30},
    {'name': 'Charlie', 'age': 20}
]

# 使用itemgetter按'age'键对字典进行排序
sorted_people = sorted(people, key=operator.itemgetter('age'))
print(sorted_people)    # [{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]

# 输出排序后的列表
for person in sorted_people:
    print(person['name'], person['age'])
    # Charlie 20
    # Alice 25
    # Bob 30


3.与 map 函数结合使用

import operator

# 创建一个列表
numbers = [1, 2, 3, 4, 5]

# 使用itemgetter提取列表中的每个元素的平方(这里仅作示例,itemgetter实际上对列表索引没太大用处)
squared = list(map(operator.itemgetter(1), map(lambda x: (x, x*x), numbers)))

# 输出结果
print(squared)  # 输出: [1, 4, 9, 16, 25]

总结

operator模块是一个功能丰富的内置工具集,提供了诸多用于执行低级运算和比较操作的函数
其中,attrgetter和itemgetter是其两大核心功能,分别用于提取对象的属性和容器中的元素。
通过这两个函数,开发者可以更加便捷地处理数据和对象,提高代码的可读性和效率。
总之,operator模块是Python编程中不可或缺的一部分,它极大地增强了Python语言的功能性和灵活性。

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐