python中 __cmp__
来源:互联网 发布:苏州java招聘 编辑:程序博客网 时间:2024/05/17 22:48
对 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)
请思考如何解决。
任务
请修改 Student 的 __cmp__ 方法,让它按照分数从高到底排序,分数相同的按名字排序。
- ?不会了怎么办
需要先比较 score,在 score 相等的情况下,再比较 name。
参考代码:
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 cmp(self.name, s.name) return -cmp(self.score, s.score)L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]print sorted(L)
1.sorted()函数会在程序运行时自动调用cmp()方法,当检测到有__cmp__()方法时则调用__cmp__()方法2.print sorted(L)相当于print sorted(L).__cmp__ python 调用sorted函数时会自动调用该方法
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 elif self.name>s.name: return 1 else: return 0 L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]print sorted(L)
0 0
- python中 __cmp__
- Python基础篇之__cmp__
- python中运行其他python
- 【Python语法】python中__name__
- Python中numpy中asarray
- Python中numpy中asarray
- python中list中方法
- Python学习中...
- Python中使用中文
- C中调用PYTHON
- 学习Python中
- python中使用getopt
- python学习中
- python中编码转换
- python中%符号详解
- Python技巧 ---- 不断更新中
- python中使用getopt
- python中合并文件
- 带参数的sqlHelper
- Linux安装mysql通用版
- 关于聊天室文字聊天(ListView 显示数据变化后滚动到最底部 )
- tomcat端口号被占用
- 你真的需要了解多种编程语言吗?
- python中 __cmp__
- C# 异常处理
- Java Applet 如何运行?
- python
- CorelDRAW中的位图颜色遮罩该怎么进行运用
- Android中的GraphicBuffer同步机制-Fence
- 【vijos】【神读入】Knights
- 十个 MongoDB 使用要点
- 手机html弹出对话框过小