python-3.x - 要重新定义哪些 Python 对象比较方法以使 sorted() 工作?

标签 python-3.x sorting redefinition

我觉得这个问题之前一定有人问过,但我找不到答案。

假设我想实现一个 Python 类,其对象可以使用 sorted() 进行排序。我是否必须重新实现所有方法,如 __lt__()__gt__() 等?最低限度是多少?换句话说,sorted() 调用哪些方法进行排序?

最佳答案

根据 documentation :

sort(*, key=None, reverse=False)
This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).

所以你只需要为你的类定义 def __lt__(self,other):

另见 Sorting HOW-TO在底部附近说:

The sort routines are guaranteed to use __lt__() when making comparisons between two objects. So, it is easy to add a standard sort order to a class by defining an __lt__() method:

关于python-3.x - 要重新定义哪些 Python 对象比较方法以使 sorted() 工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68173281/

相关文章:

java - 当使用组合而不是继承时,Comparator<T> 的替代方案是什么?

c++ - 错误 : 'int main(int, char**)' previously defined here in C++

c++ - 标题保护 C++ 的“类”类型重新定义错误

c++ - 在同一项目中使用两个不同的数学库会使Visual C++困惑

python - OpenCV在视频中查找卡住的帧

Python:如何异步 for 循环

python - 使用 scipy optimize 进行最优控制

C++ 运算符 < 重载

c - c中使用指针的交换排序算法

python - 错误 : sqlite3. 操作错误 : no such table: main. m