Python中 __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

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

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值