cmp参数在内置排序函数中的正确用法是什么?[python 2.7]

2024-04-27 11:36:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道sorted()中还有三个附加参数:cmp、key、reverse

我很清楚如何使用键和反转。Key可以对其内容项有多个子项的列表进行快速排序,并且只需将结果反转即可。例如:

>>> L1 = [('mama','1'),('papa','2'),('son','0')]
>>> L1 = sorted(L1, key = lambda x: x[1], reverse = True)
>>> L1
[('papa', '2'), ('mama', '1'), ('son', '0')]

但是到目前为止,我还没有弄清楚如何正确地使用cmp,尽管我已经阅读了官方文档。有谁能为sorted()中的cmp参数提供一个很好的用例吗?在


Tags: lambdakeyl1内容列表参数排序reverse
3条回答

cmp是用于提供自定义排序顺序的原始参数,在python2.4引入key之前,它是唯一的参数。key总是比cmp更有效(甚至在python2.4之前,鼓励使用Decorate-Sort-Undecorate习惯用法;引入key参数以简化其实现),并且在python3中完全取消了对cmp的支持。在

因此,cmp没有单独的用例;它只是在离开之前与key共存一段时间。在

根据Python Docs

cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument

当你对一组元素进行排序时,你会将它们相互比较(这取决于排序算法),以找出它们将按什么顺序排序。这是cmp开始行动的地方。在

cmp参数接受一个接受两个参数的函数作为参数。函数将返回第一项是否大于、小于或等于第二项。在

但使用这种方法效率很低,因为每次比较都必须调用它。在

引用Python - Sorting wiki

Many constructs given in this HOWTO assume Python 2.4 or later. Before that, there was no sorted()builtin and list.sort() took no keyword arguments. Instead, all of the Py2.x versions supported a cmp parameter to handle user specified comparison functions.

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__ methods).

In Py2.x, sort allowed an optional function which can be called for doing the comparisons. That function should take two arguments to be compared and then return a negative value for less-than, return zero if they are equal, or return a positive value for greater-than. For example, we can do:

>>> def numeric_compare(x, y):
        return x - y
>>> sorted([5, 2, 4, 1, 3], cmp=numeric_compare)
[1, 2, 3, 4, 5]

注意:在Python2.7中,我们有一个名为^{}的函数,可用于将cmp函数转换为key函数。在

相关问题 更多 >