如何在 Python 3 中使用自定义比较函数? [英] How to use a custom comparison function in Python 3?

查看:32
本文介绍了如何在 Python 3 中使用自定义比较函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<预><代码>>>>x=['kar','htar','har','ar']>>>>>>排序(x)['ar', 'har', 'htar', 'kar']>>>>>>排序(x,cmp =自定义排序)['kar', 'htar', 'har', 'ar']

因为,在我的语言中,辅音是跟这个顺序一起的

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

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

<预><代码>>>>排序(x,cmp =自定义排序)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中类型错误:cmp"是此函数的无效关键字参数

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

注意:我用"k"、"kh"等简化了,实际字符是Unicodes甚至更复杂,有时辅音前后有元音,我做了自定义比较功能,所以那部分没问题.唯一的问题是我无法将自定义比较函数传递给 sorted 或 .sort

解决方案

使用 key 参数(并遵循 recipe 关于如何将旧的 cmp 函数转换为 key 函数).

functools 有一个函数 cmp_to_keydocs.python.org/3.6/library/functools.html#functools.cmp_to_key

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"

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?

Note: I simplified by using "k", "kh", etc. Actual characters are Unicodes and even more complicated, sometimes there is vowels comes before and after consonents, I've done custom comparison function, So that part is ok. Only the problem is I could not pass my custom comparison function to sorted or .sort

解决方案

Use the key argument (and follow the recipe on how to convert your old cmp function to a key function).

functools has a function cmp_to_key mentioned at docs.python.org/3.6/library/functools.html#functools.cmp_to_key

这篇关于如何在 Python 3 中使用自定义比较函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆