如何在Python 3中使用自定义比较功能? [英] How to use a custom comparison function in Python 3?
问题描述
在 Python 2.x 中,我可以将自定义函数传递给sort和.sort函数
In Python 2.x, I could pass custom function to sorted and .sort functions
>>> x=['kar','htar','har','ar']
>>>
>>> sorted(x)
['ar', 'har', 'htar', 'kar']
>>>
>>> sorted(x,cmp=customsort)
['kar', 'htar', 'har', 'ar']
因为,在我的语言中,辅音是随此顺序提供的
Because, in My language, consonents are comes with this order
"k","kh",....,"ht",..."h",...,"a"
但是在 Python 3.x 中,看起来我无法传递cmp
关键字
But In Python 3.x, looks like I could not pass cmp
keyword
>>> 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
还有其他选择吗?还是我应该编写自己的排序函数?
Is there any alternatives or should I write my own sorted function too?
注意:我通过使用"k","kh"等进行了简化.实际字符是Unicode,甚至更复杂,有时在辅音前后都有元音,所以我完成了自定义比较功能,因此那部分还可以.唯一的问题是我无法将自定义比较功能传递给sort或.sort
推荐答案
Use the key
argument (and follow the recipe on how to convert your old cmp
function to a key
function).
functools
具有 docs.python中提到的函数cmp_to_key
. .org/3.6/library/functools.html#functools.cmp_to_key
functools
has a function cmp_to_key
mentioned at docs.python.org/3.6/library/functools.html#functools.cmp_to_key
这篇关于如何在Python 3中使用自定义比较功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!