当前位置:   article > 正文

Python 自定义类的排序_python重写排序算法

python重写排序算法

Python 里面自定义类的时候, 一般需要重写几个方法, __init__ 一般是构造函数

这里面有一个__cmp__() 是比较函数, 重写它的时候,一定要记得返回值有三个,0,±1  !! 而不是返回0,1   这里没有注意,导致在排序的时候,一直出错啊,QAQ

或者直接使用内置函数 cmp() 来返回就行

  1. def __cmp__(self,other):
  2. if self.age<other.age:
  3. return -1
  4. elif self.age==other.age:
  5. return 0
  6. else:
  7. return


上述的等价于:

这样再重写了这个__cmp__ 函数之后,就可以为类列表排序了

  1. def __cmp__(self,other):
  2. return cmp(self.age,other.age)


看例子:

  1. class Prople:
  2. """docstring for Prople"""
  3. def __init__(self,n,a):
  4. self.name=n
  5. self.age=a
  6. def __cmp__(self,other):
  7. return cmp(self.age,other.age)
  8. def __str__(self):
  9. return self.name+" "+str(self.age)
  10. p=Prople("liu",60)
  11. pp=Prople("li",50)
  12. li=[]
  13. li.append(p)
  14. li.append(pp)
  15. print sorted(li)[0]

这次老老实实的记住了!! 排序坑了好长时间。。。。 伤不起。。。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/177717
推荐阅读
相关标签
  

闽ICP备14008679号