網站首頁 編程語言 正文
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
函數的返回值是布爾哦
原文鏈接:https://blog.csdn.net/A156348933/article/details/86686190
相關推薦
- 2023-03-20 C#中如何生成安裝包_C#教程
- 2022-07-10 docker的安裝及常用命令
- 2022-04-08 Unity?UGUI?按鈕綁定事件的?4?種方式匯總_C#教程
- 2023-10-15 webrtc用clang編譯支持h264,支持msvc調用庫
- 2024-03-03 ElementUi tab組件切換導致echarts寬度變窄問題
- 2022-07-18 Kotlin 正確退出 foreach、foreachIndexed 循環函數
- 2023-07-24 利用keyup事件實現input框輸入0-1之間的數字且最多只能保留2位小數
- 2022-03-01 show-overflow-tooltip實現表格列內容過長顯示提示
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支