python中的cmp
① 新手學習python3.2 有關cmp
The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)
大意就是cmp()函數已經「離開」了,如果你真的需要cmp()函數,可以用表達式(a > b) - (a < b)代替cmp(a,b)。
② python3.2.2版本中的cmp()函數
3開始沒這個函數了,官方文檔是這么寫的
The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)
大意就是cmp()函數已經「離開」了,如果你真的需要cmp()函數,你可以用表達式(a > b) - (a < b)代替cmp(a,b)
③ python中比較大小的偏函數中,為什麼還要寫一個'cmp=',
3開始沒這個函數了,官方文檔是這么寫的
The cmp() function should be treated as gone, and the __cmp__() special method is no longer supported. Use __lt__() for sorting, __eq__() with __hash__(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)
大意就是cmp()函數已經「離開」了,如果你真的需要cmp()函數,你可以用表達式(a > b) - (a < b)代替cmp(a,b)
④ 在python 3.5中,cmp(a,b)被代替為(a>b)-(a<b),請解釋下(a>b)-(a<b)是什麼意思
原來的cmp函數,cmp(a,b):如果 a < b 返回 -1, 如果 a == b 返回 0, 如果 a > b 返回 1
計算機中判斷結果True用1表示,False用0表示。
我們先不妨設a>b,
那麼a >b=1,a<b=0
那麼(a>b)-(a<b)=0
同理可得到a==b輸出0,a<b輸出-1
⑤ 關於python的覆蓋__cmp__的兩點問題
__cmp__
對 int、str 等內置數據類型排序時,Python的 sorted() 按照默認的比較函數 cmp 排序,但是,如果對一組 Student 類的實例排序時,就必須提供我們自己的特殊方法 __cmp__():
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return '(%s: %s)' % (self.name, self.score)
__repr__ = __str__
def __cmp__(self, s):
if self.name < s.name:
return -1
elif self.name > s.name:
return 1
else:
return 0
上述 Student 類實現了__cmp__()方法,__cmp__用實例自身self和傳入的實例 s 進行比較,如果 self 應該排在前面,就返回 -1,如果 s 應該排在前面,就返回1,如果兩者相當,返回 0。
Student類實現了按name進行排序:
>>> L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 77)]
>>> print sorted(L)
[(Alice: 77), (Bob: 88), (Tim: 99)]
注意: 如果list不僅僅包含 Student 類,則 __cmp__ 可能會報錯:
L = [Student('Tim', 99), Student('Bob', 88), 100, 'Hello']
print sorted(L)
請思考如何解決。
class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score
def __str__(self):
return '(%s: %s)' % (self.name, self.score)
__repr__ = __str__
def __cmp__(self, s):
if(self.score<s.score):
return 1
if(self.score>s.score):
return -1
if(self.score==s.score):
if(self.name>s.name):
return 1;
if(self.name<s.name):
return -1
return 0
L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
print sorted(L)
⑥ python compare函數
cmp是python的內建函數.
cmp(x,y) 用於 compare x 和 y的值.
sort(cmp)只是用於說明,python中函數也是可以作為參數傳入其他函數來進行調用的,排序的依據就是cmp.