TypeError: 'cmp' is an invalid keyword argument for this function
TypeError: 'cmp' is an invalid keyword argument for this function
我正在使用 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 中的这个错误,我将不胜感激。
您应该尝试将 cmp
函数重写为 key 函数。在这种情况下,看起来您可以简单地 return counter()
函数输出 one 元素:
def my_key(elem):
counter = lambda x, items: sum(list(x).count(xx) for xx in items)
return counter(elem, [2, 3, 4, 5]), len(elem)
我冒昧地将 reduce(...)
代码替换为 sum()
函数,这是一种对一系列整数求和的更加紧凑和可读的方法。
上面也将首先按 counter()
的输出排序,如果出现平局,则按每个排序元素的长度排序。
但是 counter
函数效率极低;我会在这里使用 Counter()
class:
from collections import Counter
def my_key(elem):
counter = lambda x, items: sum(Counter(i for i in x if i in items).values())
return counter(elem, {2, 3, 4, 5}), len(elem)
此功能将在 Python 2 和 3 中工作:
sorted(zip(tracks, self.mapping[idx][track_selection[-1]].iloc[0]),
key=lambda x: my_key(x[1]))
如果不能,您可以使用 cmp_to_key()
utility function 调整您的 cmp
参数,但请注意这不是理想的解决方案(它会影响性能)。
来自 python 文档
In Python 2.7, the functools.cmp_to_key() function was added to the
functools module.
python3 中也有该功能。
只需用 cmp_to_key
包装您的 cmp 函数
from functools import cmp_to_key
...
...key=cmp_to_key(my_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 中的这个错误,我将不胜感激。
您应该尝试将 cmp
函数重写为 key 函数。在这种情况下,看起来您可以简单地 return counter()
函数输出 one 元素:
def my_key(elem):
counter = lambda x, items: sum(list(x).count(xx) for xx in items)
return counter(elem, [2, 3, 4, 5]), len(elem)
我冒昧地将 reduce(...)
代码替换为 sum()
函数,这是一种对一系列整数求和的更加紧凑和可读的方法。
上面也将首先按 counter()
的输出排序,如果出现平局,则按每个排序元素的长度排序。
但是 counter
函数效率极低;我会在这里使用 Counter()
class:
from collections import Counter
def my_key(elem):
counter = lambda x, items: sum(Counter(i for i in x if i in items).values())
return counter(elem, {2, 3, 4, 5}), len(elem)
此功能将在 Python 2 和 3 中工作:
sorted(zip(tracks, self.mapping[idx][track_selection[-1]].iloc[0]),
key=lambda x: my_key(x[1]))
如果不能,您可以使用 cmp_to_key()
utility function 调整您的 cmp
参数,但请注意这不是理想的解决方案(它会影响性能)。
来自 python 文档
In Python 2.7, the functools.cmp_to_key() function was added to the functools module.
python3 中也有该功能。
只需用 cmp_to_key
包装您的 cmp 函数from functools import cmp_to_key
...
...key=cmp_to_key(my_cmp)...