对 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))
输出错误:
TypeError: ‘<’ not supported between instances of ‘Student’ and
‘Student’
在Python 3.x, 取消了 cmp 参数, 只保留了Key Function参数。将最后一行代码改为:
print(sorted(L, key=lambda Student:(Student.name)))
结果为:
[(Alice: 77), (Bob: 88), (Tim: 99)]
上述 Student 类实现了__cmp__()方法,__cmp__用实例自身self和传入的实例 s 进行比较,如果 self 应该排在前面,就返回 -1,如果 s 应该排在前面,就返回1,如果两者相当,返回 0。
任务:
修改 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.score < s.score:
return -1
elif self.score > s.score:
return 1
else:
if self.name < s.name:
return -1
return 0
L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
print(sorted(L, key=lambda Student:(-Student.score, Student.name)))
结果为:
[(Alice: 99), (Tim: 99), (Bob: 88)]
大家加油!
学习链接: https://www.imooc.com/code/6251