这在 Python 2.7 中完美运行
def some_compare_func(x, y):
....
a = sorted(some_list, lambda x, y: some_compare_func(x, y))
但是,在 Python 3.x 中同样会出现此错误。
TypeError: sorted expected 1 arguments, got 2
是否有一种方法可以使用同时适用于 Python 2.7 和 3.x 的排序函数进行排序?
最佳答案
可以转换python2风格cmp
至key
使用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))
检查https://docs.python.org/3/howto/sorting.html#the-old-way-using-the-cmp-parameter了解更多详情
关于python - Python 3 中排序函数与比较函数的等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57429471/