小编典典

如何在Python 3中使用自定义比较功能?

python

Python 2.x中 ,我可以将自定义函数传递给sort和.sort函数

>>> x=['kar','htar','har','ar']
>>>
>>> sorted(x)
['ar', 'har', 'htar', 'kar']
>>> 
>>> sorted(x,cmp=customsort)
['kar', 'htar', 'har', 'ar']

因为在 我的 语言中,辅音是与此顺序一起出现的

"k","kh",....,"ht",..."h",...,"a"

但是在 Python 3.x中 ,看起来我无法传递cmp关键字

>>> sorted(x,cmp=customsort)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'cmp' is an invalid keyword argument for this function

有其他选择吗?或者我也应该编写自己的排序函数吗?

注意:我通过使用“ k”,“
kh”等进行了简化。实际字符是Unicode,甚至更复杂,有时在辅音前后都有元音,所以我完成了自定义比较功能,因此这一部分还可以。唯一的问题是我无法将自定义比较功能传递给sort或.sort


阅读 259

收藏
2020-12-20

共1个答案

小编典典

使用key参数(并按照配方上如何将旧的转换cmp功能的key功能)。

functools``cmp_to_keydocs.python.org/3.6/library/functools.html#functools.cmp_to_key中提到了一个功能

2020-12-20