问题描述

当小伙伴们愉快地用Python2中list的sort()方法的cmp参数排序时:

nums = [1, 3, 2, 4]
nums.sort(cmp=lambda a, b: a - b)
print(nums)  # [1, 2, 3, 4]

却发现在Python3下竟然报错了:

Traceback (most recent call last):
  File "temp.py", line 2, in <module>
    nums.sort(cmp=lambda a, b: a - b)
TypeError: 'cmp' is an invalid keyword argument for this function

找不到cmp参数?WTF?还怎么愉快玩耍?

原因分析

马上去看官方文档,Python2下的sort():

sort(cmp=None, key=None, reverse=False)

再看看Python3下:

sort(*, key=None, reverse=None)

好把Python3下真的把cmp参数给取消掉了。这么取消掉总得给个原因吧?貌似官方文档里还真给出了原因:

In Py3.0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__() magic method).

意思就是为了简化和统一Python语言,于是就把sort()方法中的cmp参数给取消掉了,真是任性。

解决方法

为了照顾到广大cmp用户的心情,Python3还是留了一条活路的,同样也在官网文档里有介绍:

The functools.cmp_to_key() utility is available to convert a 2.x style cmp function to a key function.

就是用functools.cmp_to_key()来曲线救国啦,废话不多说,直接上代码:

from functools import cmp_to_key

nums = [1, 3, 2, 4]
nums.sort(key=cmp_to_key(lambda a, b: a - b))
print(nums)  # [1, 2, 3, 4]

还是熟悉的味道有木有!千万别忘了import哦~

参考