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
    评论
Python 3中的 `operator` 模块提供了一组函数,用于对内置类型(例如数字、字符串和列表)进行操作。常见的 `operator` 函数如下: 1. 算术运算符函数 - `operator.add(a, b)`:返回 `a + b` 的值。 - `operator.sub(a, b)`:返回 `a - b` 的值。 - `operator.mul(a, b)`:返回 `a * b` 的值。 - `operator.truediv(a, b)`:返回 `a / b` 的值。 - `operator.floordiv(a, b)`:返回 `a // b` 的值。 - `operator.mod(a, b)`:返回 `a % b` 的值。 - `operator.pow(a, b)`:返回 `a ** b` 的值。 2. 比较运算符函数 - `operator.eq(a, b)`:返回 `a == b` 的值。 - `operator.ne(a, b)`:返回 `a != b` 的值。 - `operator.lt(a, b)`:返回 `a < b` 的值。 - `operator.le(a, b)`:返回 `a <= b` 的值。 - `operator.gt(a, b)`:返回 `a > b` 的值。 - `operator.ge(a, b)`:返回 `a >= b` 的值。 3. 逻辑运算符函数 - `operator.not_(a)`:返回 `not a` 的值。 - `operator.and_(a, b)`:返回 `a and b` 的值。 - `operator.or_(a, b)`:返回 `a or b` 的值。 4. 位运算符函数 - `operator.and_(a, b)`:返回 `a & b` 的值。 - `operator.or_(a, b)`:返回 `a | b` 的值。 - `operator.xor(a, b)`:返回 `a ^ b` 的值。 - `operator.invert(a)`:返回 `~a` 的值。 - `operator.lshift(a, b)`:返回 `a << b` 的值。 - `operator.rshift(a, b)`:返回 `a >> b` 的值。 5. 序列运算符函数 - `operator.concat(a, b)`:返回 `a + b` 的值。 - `operator.contains(a, b)`:返回 `b in a` 的值。 - `operator.countOf(a, b)`:返回 `a.count(b)` 的值。 - `operator.delitem(a, b)`:删除 a[b] 的值。 - `operator.getitem(a, b)`:返回 a[b] 的值。 - `operator.setitem(a, b, c)`:将 a[b] 的值设置为 c。 其中,函数名与对应的运算符相对应。例如,`operator.add(a, b)` 对应加法运算符 `+`,`operator.eq(a, b)` 对应等于运算符 `==`。这些函数可以用于简化代码,特别是当需要在函数参数中传递运算符时。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值