【发布时间】:2011-02-01 16:22:43
【问题描述】:
在 Python 2.x 中,我可以将自定义函数传递给 sorted 和 .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,甚至更复杂,有时元音在辅音前后,我做了自定义比较功能,所以那部分没问题。唯一的问题是我无法将自定义比较函数传递给 sorted 或 .sort
【问题讨论】:
-
你试过
sorted(x)吗? -
@SilentGhost,为了确保,我又试了一次,当然不行,因为 my 原始语言不在操作系统支持的区域设置列表中进行排序。
-
您可以将您的 cmp 包装为一个关键函数。在 HowToSorting 站点中搜索 cmp_to_key。
标签: python sorting python-3.x