对 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
L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 77)]
print sorted(L)
上述 Student 类实现了__cmp__()方法,__cmp__用实例自身self和传入的实例 s 进行比较,如果 self 应该排在前面,就返回 -1,如果 s 应该排在前面,就返回1,如果两者相当,返回 0。
控制台打印结果
/usr/bin/python2.7 /home/l/tmp/foomodule/1.py
[(Alice: 77), (Bob: 88), (Tim: 99)]
注意: 如果list不仅仅包含 Student 类,则 __cmp__可能会报错:
L = [Student('Tim', 99), Student('Bob', 88), 100, 'Hello']
print sorted(L)
Python3里cmp没有了,用operator模块里的一系列方法代替,例如operator.lt(a,b)表示判断a<b,operator.gt(a,b)判断a>b,operator.eq(a,b)判断a==b。返回值都是布尔值,其他的还有不等于.ne,大于等于和小于等于.ge .le。以及对应的特殊方法operator.__**__(self, x)。
描述
cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。
返回值
如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1
实例
以下展示了使用 cmp() 方法的实例:
#!/usr/bin/python
print "cmp(80, 100) : ", cmp(80, 100)
print "cmp(180, 100) : ", cmp(180, 100)
print "cmp(-80, 100) : ", cmp(-80, 100)
print "cmp(80, -100) : ", cmp(80, -100)
以上实例运行后输出结果为:
cmp(80, 100) : -1
cmp(180, 100) : 1
cmp(-80, 100) : -1
cmp(80, -100) : 1
参考地址
Python 3.X 的版本中已经没有 cmp 函数,如果你需要实现比较功能,需要引入 operator 模块,适合任何对象,包含的方法有
operator.lt(a, b)
operator.le(a, b)
operator.eq(a, b)
operator.ne(a, b)
operator.ge(a, b)
operator.gt(a, b)
operator.__lt__(a, b)
operator.__le__(a, b)
operator.__eq__(a, b)
operator.__ne__(a, b)
operator.__ge__(a, b)
operator.__gt__(a, b)
实例
>>> import operator
>>> operator.eq('hello', 'name');
False
>>> operator.eq('hello', 'hello');
True







网友评论