python - 类型错误 : 'cmp' is an invalid keyword argument for this function

标签 python sorting python-3.x python-2.x cmp

我正在使用 Python3,但脚本与此版本不兼容,我遇到了一些错误。现在我对 cmp 参数有疑问。这是代码

def my_cmp(x,y):
    counter = lambda x, items: reduce(lambda a,b:a+b, [list(x).count(xx) for xx in items])
    tmp =  cmp(counter(x, [2,3,4,5]), counter(y, [2,3,4,5]))
    return tmp if tmp!=0 else cmp(len(x),len(y)) 

for i, t in enumerate([tmp[0] for tmp in sorted(zip(tracks, self.mapping[idx][track_selection[-1]].iloc[0]), cmp=my_cmp, key=lambda x:x[1])]):
    img[i,:len(t)] = t

如果能帮助我解决 Python3 中的这个错误,我将不胜感激。

最佳答案

来自 python 文档

In Python 2.7, the functools.cmp_to_key() function was added to the functools module.

python 3 中也可用的函数。

只需用 cmp_to_key 包装你的 cmp 函数

from functools import cmp_to_key

...

...key=cmp_to_key(my_cmp)...

关于python - 类型错误 : 'cmp' is an invalid keyword argument for this function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28502774/

相关文章:

python - Seaborn 折线图样式导致重复的图例条目

python - 在文件中显式写入换行符

python - 如何从 Python 中的唯一列表访问下一个元素

python-3.x - 如何用 sympy 声明自然符号?

c++ - Maya MFnPlugin::registerUI 调用 Python 而不是 MEL 脚本

python - 使用 matplotlib 的三角形形式的多个子图

Mysql 排序 - 排序一些而不是其他?

mongodb展开并排序嵌套在文档数组中的数组

sorting - 如何对文本 block 进行排序?

python - QCoreApplication.processEvents 行为