溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python3中cmp如何實(shí)現(xiàn)

發(fā)布時(shí)間:2022-02-09 14:26:08 來源:億速云 閱讀:232 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要為大家展示了“python3中cmp如何實(shí)現(xiàn)”,內(nèi)容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“python3中cmp如何實(shí)現(xiàn)”這篇文章吧。

python3 cmp實(shí)現(xiàn)

python3移除了cmp()函數(shù),但提供了六個(gè)豐富的比較運(yùn)算符,詳見此處

import operator       #首先要導(dǎo)入運(yùn)算符模塊
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函數(shù)或者sorted函數(shù)來實(shí)現(xiàn)排序。'''
	def __init__(self, name, age):
        self.name = name
        self.age = age
    def __cmp__(self, other):
        return cmp(self.age, other.age)

cmp()函數(shù)實(shí)現(xiàn)的注解

bool僅僅是一個(gè)int子類,那么True和False可以理解為1和0區(qū)別。

因?yàn)槿绻谝粋€(gè)參數(shù)小于第二個(gè)參數(shù),cmp返回負(fù)值,如果參數(shù)相等則返回0,否則返回正值,可以看到False - False == 0,True - False == 1和False - True == -1為cmp提供正確的返回值。

python3 使用cmp函數(shù)報(bào)錯(cuò)

python3中已經(jīng)不使用cmp函數(shù)進(jìn)行比較大小

使用operator模塊

import operator
lt(a,b) 相當(dāng)于 a<b     從第一個(gè)數(shù)字或字母(ASCII)比大小  
le(a,b)相當(dāng)于a<=b 
eq(a,b)相當(dāng)于a==b     字母完全一樣,返回True, 
ne(a,b)相當(dāng)于a!=b 
gt(a,b)相當(dāng)于a>b 
ge(a,b)相當(dāng)于 a>=b

函數(shù)的返回值是布爾哦

以上是“python3中cmp如何實(shí)現(xiàn)”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI