Python3 operator模块关联代替Python2 cmp() 函数

Python2 cmp() 函数

描述
cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。

Python cmp() 函数
描述
cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。
语法及参数
cmp( x, y )
x -- 数值表达式
y -- 数值表达式
返回值
如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。

Python3 operator模块

描述
python3中使用operator模块进行字符串、数字两个变量的大小比较;在使用operator模块时需要提前导入该模块,使用命令import operator来进行导入
语法及参数
operator.eq(x,y)
operator.ne(x,y)
operator.lt(x,y)
operator.le(x,y)
operator.gt(x,y)
operator.ge(x,y)

返回值
>>> operator.eq("a","a");
True
>>> operator.lt("c","b");
False
>>> operator.gt("c","b");
True
>>> operator.ne("c","b");
True
>>> operator.le("c","b");
False
>>> operator.ge("c","b");
True

Python3 cmp()函数报错描述

Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> cmp(1,8)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'cmp' is not defined

Python3 报错解决方法

python 3.4.3 的版本中已经没有cmp(x,y)函数,被operator模块代替,使用operator完美解决该报错!!!

  

原文地址:https://www.cnblogs.com/Wolf-Dreams/p/10597620.html