Python 3 中排序函数与比较函数的等效项

Met*_*est 1 python sorting python-2.7 python-3.x

这在 Python 2.7 中完美运行

def some_compare_func(x, y):
  ....

a = sorted(some_list, lambda x, y: some_compare_func(x, y))
Run Code Online (Sandbox Code Playgroud)

然而,在 Python 3.x 中同样会出现此错误。

TypeError: sorted expected 1 arguments, got 2
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以在 Python 2.7 和 3.x 中使用排序函数进行排序?

Sun*_*tha 5

您可以将 python2 样式转换cmpkey使用functools.cmp_to_key()

以下代码应该在 python2 和 python3 中都可以工作

def some_compare_func(x, y):
  ....

import functools
a = sorted(some_list, key=functools.cmp_to_key(some_compare_func))
Run Code Online (Sandbox Code Playgroud)

检查https://docs.python.org/3/howto/sorting.html#the-old-way-using-the-cmp-parameter了解更多详细信息