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.