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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值