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完美解決該報錯!!!

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM