如何在Python 3中使用自定义比较函数?

Python 2.x中 ,我可以将自定义函数传递给排序函数和.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”等进行了简化。实际的字符是Unicodes,甚至更复杂,有时在元音前后有元音,我已经完成了自定义比较功能,所以这部分是可以的。 只有问题是我无法将自定义比较函数传递给排序或.sort


使用key参数(并按照关于如何将旧的cmp函数转换为key函数的配方)。


使用key关键字和functools.cmp_to_key来转换您的比较函数:

sorted(x, key=functools.cmp_to_key(customsort))

您不需要使用一个惯例(),您需要一个将每个单词翻译成Python已经知道如何排序的功能。 例如,您可以将每个单词翻译成一个数字列表,其中每个数字表示每个字母在您的字母表中出现的位置。 像这样的东西:

my_alphabet = ['a', 'b', 'c']

def custom_key(word):
   numbers = []
   for letter in word:
      numbers.append(my_alphabet.index(letter))
   return numbers

x=['cbaba', 'ababa', 'bbaa']
x.sort(key=custom_key)

由于您的语言包含多字符字母,因此您的custom_key函数显然需要更复杂。 这应该给你一个总体思路。

链接地址: http://www.djcxy.com/p/70757.html

上一篇: How to use a custom comparison function in Python 3?

下一篇: Sort a list by multiple attributes?