Python3 operator 模块

Python2.x 版本中,使用 cmp() 函数来比较两个列表、数字或字符串等的大小关系。

Python 3.X 的版本中已经没有 cmp() 函数,如果你需要实现比较功能,需要引入 operator 模块,适合任何对象,包含的方法有:

operator 模块包含的方法

operator.lt(a, b)
operator.le(a, b)
operator.eq(a, b)
operator.ne(a, b)
operator.ge(a, b)
operator.gt(a, b)
operator.__lt__(a, b)
operator.__le__(a, b)
operator.__eq__(a, b)
operator.__ne__(a, b)
operator.__ge__(a, b)
operator.__gt__(a, b)

operator.lt(a, b)a &lt b 相同, operator.le(a, b)a <= b 相同,operator.eq(a, b)a == b 相同,operator.ne(a, b)a != b 相同,operator.gt(a, b)a > b 相同,operator.ge(a, b)a >= b 相同。

实例

# 导入 operator 模块
import operator

# 数字
x = 10
y = 20

print("x:",x, ", y:",y)
print("operator.lt(x,y): ", operator.lt(x,y))
print("operator.gt(y,x): ", operator.gt(y,x))
print("operator.eq(x,x): ", operator.eq(x,x))
print("operator.ne(y,y): ", operator.ne(y,y))
print("operator.le(x,y): ", operator.le(x,y))
print("operator.ge(y,x): ", operator.ge(y,x))
print()

# 字符串
x = "Google"
y = "Runoob"

print("x:",x, ", y:",y)
print("operator.lt(x,y): ", operator.lt(x,y))
print("operator.gt(y,x): ", operator.gt(y,x))
print("operator.eq(x,x): ", operator.eq(x,x))
print("operator.ne(y,y): ", operator.ne(y,y))
print("operator.le(x,y): ", operator.le(x,y))
print("operator.ge(y,x): ", operator.ge(y,x))
print()

# 查看返回值
print("type((operator.lt(x,y)): ", type(operator.lt(x,y)))

以上代码输出结果为:

x: 10 , y: 20
operator.lt(x,y):  True
operator.gt(y,x):  True
operator.eq(x,x):  True
operator.ne(y,y):  False
operator.le(x,y):  True
operator.ge(y,x):  True

x: Google , y: Runoob
operator.lt(x,y):  True
operator.gt(y,x):  True
operator.eq(x,x):  True
operator.ne(y,y):  False
operator.le(x,y):  True
operator.ge(y,x):  True

比较两个列表:

实例

# 导入 operator 模块
import operator

a = [1, 2]
b = [2, 3]
c = [2, 3]
print("operator.eq(a,b): ", operator.eq(a,b))
print("operator.eq(c,b): ", operator.eq(c,b))

以上代码输出结果为:

operator.eq(a,b):  False
operator.eq(c,b):  True

运算符函数

operator 模块提供了一套与 Python 的内置运算符对应的高效率函数。例如,operator.add(x, y) 与表达式 x+y 相同。

函数包含的种类有:对象的比较运算、逻辑运算、数学运算以及序列运算。

对象比较函数适用于所有的对象,函数名根据它们对应的比较运算符命名。

许多函数名与特殊方法名相同,只是没有双下划线。为了向后兼容性,也保留了许多包含双下划线的函数,为了表述清楚,建议使用没有双下划线的函数。

实例

# Python 实例
# add(), sub(), mul()

# 导入  operator 模块
import operator

# 初始化变量
a = 4

b = 3

# 使用 add() 让两个值相加
print ("add() 运算结果 :",end="");
print (operator.add(a, b))

# 使用 sub() 让两个值相减
print ("sub() 运算结果 :",end="");
print (operator.sub(a, b))

# 使用 mul() 让两个值相乘
print ("mul() 运算结果 :",end="");
print (operator.mul(a, b))

以上代码输出结果为:

add() 运算结果 :7
sub() 运算结果 :1
mul() 运算结果 :12