目录:
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
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)
处理自定义类实例列表的排序。
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
from operator import getitem, contains, concat
lst = [1, 2, 3]
# 获取元素
print(getitem(lst, 1)) # 输出: 2, 等价于 lst[1]
from operator import getitem, contains, concat
lst = [1, 2, 3]
# 判断元素是否在序列中
print(contains(lst, 2)) # 输出: True, 等价于 2 in lst
from operator import getitem, contains, concat
lst = [1, 2, 3]
# 连接两个序列
print(concat(lst, [4, 5])) # 输出: [1, 2, 3, 4, 5], 等价于 lst + [4,5]
用于生成一个调用对象指定方法的函数,便于批量处理。
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']]
↶ 返回首页 ↶