Python3中的operator模块提供了一系列运算符函数,可以帮助开发者快速实现某些常见的函数。它的函数形式可以替代普通的运算符,使代码更加简洁。
operator模块中的函数大致可以分为四类:
- 算术运算符:add()、sub()、mul()、truediv()、floordiv()、mod()、pow()、neg()、pos()、abs()、lt()、le()、eq()、ne()、gt()、ge()
- 位运算符:and_()、or_()、xor()、invert()、lshift()、rshift()
- 序列相关:concat()、contains()、countOf()、indexOf()、getitem()、setitem()、delitem()
- 其它:truth()、is_()、not_()
下面通过实例来说明如何使用这些函数:
# 导入operator模块 import operator # 算术运算 x = 5 y = 3 # 加法 print(operator.add(x, y)) # 8 # 减法 print(operator.sub(x, y)) # 2 # 乘法 print(operator.mul(x, y)) # 15 # 除法 print(operator.truediv(x, y)) # 1.6666666666666667 # 求余 print(operator.mod(x, y)) # 2 # 幂运算 print(operator.pow(x, y)) # 125 # 比较大小 print(operator.lt(x, y)) # False # 取负 print(operator.neg(x)) # -5 # 位运算 x = 0b101 y = 0b110 # 与 print(operator.and_(x, y)) # 0b100 # 或 print(operator.or_(x, y)) # 0b111 # 异或 print(operator.xor(x, y)) # 0b011 # 左移 print(operator.lshift(x, 1)) # 0b1010 # 右移 print(operator.rshift(x, 1)) # 0b10 # 序列相关 # 列表 list1 = [1, 2, 3] list2 = [4, 5, 6] # 连接 print(operator.concat(list1, list2)) # [1, 2, 3, 4, 5, 6] # 是否包含 print(operator.contains(list1, 2)) # True # 数量 print(operator.countOf(list1, 2)) # 1 # 位置 print(operator.indexOf(list1, 2)) # 1 # 获取item print(operator.getitem(list1, 1)) # 2 # 设置item operator.setitem(list1, 1, 4) print(list1) # [1, 4, 3] # 删除item operator.delitem(list1, 1) print(list1) # [1, 3] # 其它 # 逻辑真值 print(operator.truth(1)) # True # 是否相等 print(operator.is_(1, 1)) # True # 逻辑非 print(operator.not_(1)) # False
以上就是operator模块中的运算符函数的使用方法,可以帮助开发者更快更好的实现代码功能,提高开发效率。