python - 使用自定义比较的排序键函数

标签 python python-3.x sorting functional-programming comparison

<分区>

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对于这个和其他技巧。

关于python - 使用自定义比较的排序键函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40053658/

相关文章:

python - 如何解决: Truncated or oversized response headers received from daemon process

python - 循环检查两个内存 View 的有效方法是什么?

python - Microsoft MSAL 是否提供资源所有者密码凭据授予授权支持?

unix - 如果使用 uniq 命令(在 shell 中),如何保持文件的格式?

java - 动态排序用户输入而不使用 Java 中的内置排序方法

java - 如何为 Dijkstra 算法实现 PriorityQueue?

python - Django - 异常类型 : NoReverseMatch

Python 类型提示 - 方法返回当前类的列表

python - 更新到 VS Code 1.66.0 后调试 Python 程序不起作用

python-3.x - NetworkX:在 DAG 中查找最长路径,返回最大的所有关系