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

查看:89
本文介绍了如何在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

推荐答案

使用key参数(并遵循

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屋!

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