本文介绍了如何在 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"是此函数的无效关键字参数

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

解决方案

使用 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?

解决方案

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 中使用自定义比较函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 01:31