温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python3中cmp如何实现

发布时间:2022-02-09 14:26:08 来源:亿速云 阅读:215 作者:小新 栏目:开发技术

这篇文章主要为大家展示了“python3中cmp如何实现”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“python3中cmp如何实现”这篇文章吧。

python3 cmp实现

python3移除了cmp()函数,但提供了六个丰富的比较运算符,详见此处

import operator       #首先要导入运算符模块
operator.gt(1,2)      #意思是greater than(大于)
operator.ge(1,2)      #意思是greater and equal(大于等于)
operator.eq(1,2)      #意思是equal(等于)
operator.le(1,2)      #意思是less and equal(小于等于)
operator.lt(1,2)      #意思是less than(小于)

PY3__cmp__ mixin类

import sys
PY3 = sys.version_info[0] >= 3
if PY3:
    def cmp(a, b):
        return (a > b) - (a < b)
    # mixin class for Python3 supporting __cmp__
    class PY3__cmp__:   
        def __eq__(self, other):
            return self.__cmp__(other) == 0
        def __ne__(self, other):
            return self.__cmp__(other) != 0
        def __gt__(self, other):
            return self.__cmp__(other) > 0
        def __lt__(self, other):
            return self.__cmp__(other) < 0
        def __ge__(self, other):
            return self.__cmp__(other) >= 0
        def __le__(self, other):
            return self.__cmp__(other) <= 0
else:
    class PY3__cmp__:
        pass
class YourClass(PY3__cmp__):
	'''自定义类,可以用list.sort函数或者sorted函数来实现排序。'''
	def __init__(self, name, age):
        self.name = name
        self.age = age
    def __cmp__(self, other):
        return cmp(self.age, other.age)

cmp()函数实现的注解

bool仅仅是一个int子类,那么True和False可以理解为1和0区别。

因为如果第一个参数小于第二个参数,cmp返回负值,如果参数相等则返回0,否则返回正值,可以看到False - False == 0,True - False == 1和False - True == -1为cmp提供正确的返回值。

python3 使用cmp函数报错

python3中已经不使用cmp函数进行比较大小

使用operator模块

import operator
lt(a,b) 相当于 a<b     从第一个数字或字母(ASCII)比大小  
le(a,b)相当于a<=b 
eq(a,b)相当于a==b     字母完全一样,返回True, 
ne(a,b)相当于a!=b 
gt(a,b)相当于a>b 
ge(a,b)相当于 a>=b

函数的返回值是布尔哦

以上是“python3中cmp如何实现”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI