cmp是python的內(nèi)建函數(shù).
創(chuàng)新互聯(lián)公司-云計(jì)算及IDC服務(wù)提供商,涵蓋公有云、IDC機(jī)房租用、綿陽(yáng)服務(wù)器托管、等保安全、私有云建設(shè)等企業(yè)級(jí)互聯(lián)網(wǎng)基礎(chǔ)服務(wù),歡迎咨詢(xún):18982081108
cmp(x,y) 用于 compare x 和 y的值.
sort(cmp)只是用于說(shuō)明,python中函數(shù)也是可以作為參數(shù)傳入其他函數(shù)來(lái)進(jìn)行調(diào)用的,排序的依據(jù)就是cmp.
numbers.sort這種用法是錯(cuò)誤的,如果你想要排序,則用如下語(yǔ)句:
num_sort=sorted(numbers,key=None,reverse=False)
新的list num_sort才是一個(gè)排序后的列表。然后,你自定義的cmp過(guò)程只能對(duì)比兩個(gè)數(shù)字,而能對(duì)比列表中的各個(gè)元素,python3解釋器不知道你要做什么,所以才會(huì)出錯(cuò)。
3開(kāi)始沒(méi)這個(gè)函數(shù)了,官方文檔是這么寫(xiě)的
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()函數(shù)已經(jīng)“離開(kāi)”了,如果你真的需要cmp()函數(shù),你可以用表達(dá)式(a b) - (a b)代替cmp(a,b)
cmp( x, y)
Compare the two objects x and y and return an integer according to the outcome. The return value is negative if x y, zero if x == y and strictly positive if x y.
比較2個(gè)對(duì)象,前者小于后者返回-1,相等則返回0,大于后者返回1.