如何在Python中创建可排序的数据类型? [英] how to make sortable datatype in Python?
问题描述
我有一堂课,代表一些领域.当对此类的实例列表进行排序时,我希望它们以特定的顺序进行排序(从每个实例中获取特定的键).我可以做list.sort(key=Classname.sortKey)
并定义一个sortKey
方法,但是我宁愿去做list.sort()
并解决它.我认为我可以通过覆盖__cmp__
来做到这一点.但是,当我与非数据类型的东西进行比较时该怎么办?我想像...
I have a class representing something with a few fields. When a list of instances of this class is sorted, I want them to be sorted in a particular order (get a particular key from each one). I can just do list.sort(key=Classname.sortKey)
and define a sortKey
method, but I'd rather just do list.sort()
and have it work out. I figure I can do this by overriding __cmp__
. However, what do I do when I'm comparing with something that is not my data type? I figure something like...
def __cmp__(self, o):
if isinstance(o, MyClass):
return cmp(self.sortKey(), o.sortKey())
return object.__cmp__(self, o) ##**wrong
但是可以代替.我不在乎它们在异构列表中采用什么顺序.我只返回0
,但是对于任何x
而不是MyClass
的实例,像MyClass(...) == x
这样的东西总是正确的.
but that works instead. I don't care what ordering they take in a heterogeneous list. I would just return 0
but then stuff like MyClass(...) == x
is always true, for any x
not an instance of MyClass
.
推荐答案
查看 http://wiki.python.org/moin/HowTo/Sorting/
您要在类中覆盖__lt__
以便使内置的sort
函数按您所描述的方式工作.
You want to override __lt__
in your class for the built in sort
function to work the way you described.
这篇关于如何在Python中创建可排序的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!