python3.2.2版本中的cmp()函数

Python08

python3.2.2版本中的cmp()函数,第1张

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)

numbers.sort这种用法是错误的,如果你想要排序,则用如下语句:

num_sort=sorted(numbers,key=None,reverse=False)

新的list num_sort才是一个排序后的列表。然后,你自定义的cmp过程只能对比两个数字,而能对比列表中的各个元素,python3解释器不知道你要做什么,所以才会出错。

原来的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