python 3 removes the cmp
parameter to sorting functions :
builtin.sorted()
and list.sort()
no longer accept the cmp
argument providing a comparison function. Use the key
argument instead.
这对于可以通过检查序列中的单个项目来确定的排序来说很好(例如 key=str.lower
)。但是,必须有两个项目进行检查以确定其顺序的自定义订单呢?
$ python2
Python 2.7.12+ (default, Sep 1 2016, 20:27:38)
[…]
>>> digits = ['3', '30', '34', '32', '9', '5']
>>> sorted(
... digits,
... cmp=(lambda a, b: cmp(a+b, b+a)),
... reverse=True)
['9', '5', '34', '3', '32', '30']
那个双参数 cmp
函数不能用单参数 key
函数代替,可以吗?
使用 functools.cmp_to_key
helper 。
>>> import functools
>>> digits = ['3', '30', '34', '32', '9', '5']
>>> sorted(
... digits,
... key=functools.cmp_to_key(lambda a, b: cmp(a+b, b+a)),
... reverse=True)
['9', '5', '34', '3', '32', '30']
Python 3 sorting functions take a ‘key’ parameter :
key
specifies a function of one argument that is used to extract a
comparison key from each list element: key=str.lower
. The default
value is None
(compare the elements directly).
functools.cmp_to_key
助手是 designed to help you transition to
that style :
functools.cmp_to_key(func)
Transform an old-style comparison function to a key function. […]
This function is primarily used as a transition tool for programs
being converted from Python 2 which supported the use of comparison
functions.
这适用于最新的 Python 2 和 Python 3。
这个技巧是通过创建一个关键函数来完成的,该函数接受一个项目
比较,并返回一个知道如何比较的自定义对象
本身由您的比较函数指定。
>>> key_func = functools.cmp_to_key(lambda a, b: cmp(a+b, b+a))
>>> key_func("32")
<functools.K object at 0x7f6781ce0980>
>>> key_func("32") < key_func("5")
True
参见 Sorting HOWTO对于这个和其他技巧。