【python 内置模块】operator

2024-01-20 00:00:00

目录:

算术运算符函数

import operator

# 加法
print(operator.add(5, 3))  # 输出: 8, 等价于 5 + 3
# 乘法
print(operator.mul(4, 2))  # 输出: 8, 等价于 4 * 2
# 真除法 (返回浮点数)
print(operator.truediv(10, 4))  # 输出: 2.5, 等价于 10 / 4
# 地板除 (返回整数)
print(operator.floordiv(10, 4))  # 输出: 2, 等价于 10 // 4
# 幂运算
print(operator.pow(2, 3))  # 输出: 8, 等价于 2 ** 3

比较运算符函数

import operator

print(operator.eq(5, 5))  # 输出: True, 等价于 5 == 5
print(operator.gt(10, 7)) # 输出: True, 等价于 10 > 7
print(operator.lt(2, 8))  # 输出: True, 等价于 2 < 8

itemgetter 按索引或键获取元素

from operator import itemgetter

students = [('Alice', 18, 90), ('Bob', 20, 85), ('Charlie', 19, 95)]
# 按年龄(索引1)排序,替代 key=lambda x: x
sorted_by_age = sorted(students, key=itemgetter(1))
print(sorted_by_age)  # 输出: [('Alice', 18, 90), ('Charlie', 19, 95), ('Bob', 20, 85)]

# 支持多字段获取
getter = itemgetter(0, 2)  # 获取姓名和成绩
for student in students:
    print(getter(student))  # 输出: ('Alice', 90), ('Bob', 85), ('Charlie', 95)

attrgetter 按属性名获取对象属性

处理自定义类实例列表的排序。

from operator import attrgetter

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

students = [Student('Alice', 20), Student('Bob', 18)]
sorted_students = sorted(students, key=attrgetter('age'))
for s in sorted_students:
    print(s.name, s.age)  # 输出: Bob 18, Alice 20

getitem 获取元素

from operator import getitem, contains, concat

lst = [1, 2, 3]

# 获取元素
print(getitem(lst, 1))  # 输出: 2, 等价于 lst[1]

contains 判断元素是否在序列中

from operator import getitem, contains, concat

lst = [1, 2, 3]

# 判断元素是否在序列中
print(contains(lst, 2))  # 输出: True, 等价于 2 in lst

concat 连接两个序列

from operator import getitem, contains, concat

lst = [1, 2, 3]

# 连接两个序列
print(concat(lst, [4, 5]))  # 输出: [1, 2, 3, 4, 5], 等价于 lst + [4,5]

methodcaller 方法调用函数

用于生成一个调用对象指定方法的函数,便于批量处理。

from operator import methodcaller

strings = ["a,b,c", "x,y,z", "1,2,3"]
split_func = methodcaller('split', ',') # 生成一个调用 split(',') 方法的函数
result = list(map(split_func, strings))
print(result)  # 输出: [['a', 'b', 'c'], ['x', 'y', 'z'], ['1', '2', '3']]

返回首页

本文总阅读量  次
皖ICP备17026209号-3
总访问量: 
总访客量: