一、sort函数
sort函数默认按从小到大的顺序排列
————————————————
sort()函数原型:
list.sort(key=None, reverse=False)、
(1) key参数
key接受的是一个只有一个形参的函数,形式如下
def f(a):
return len(a)
key接受的函数返回值,表示此元素的权值,sort将按照权值大小进行排序
list = ['aa', 'bbb', 'cccc', 'd']
def compare(a):
return len(a)
list.sort(key=compare)
print(list)
结果:['d', 'aa', 'bbb', 'cccc']
(2) reverse参数
reverse接受的是一个bool类型的值 (Ture or False),表示是否颠倒排列顺序,一般默认的是False,注意第一个字母是大写的
二、cmp
在python2里面的sort()函数是有三个参数的:
L.sort(cmp=None, key=None, reverse=False)
其中的cmp在python里面已经被删除了,但是还是说明一下
cmp参数:
cmp接受一个函数,拿整形举例,形式为:
def f(a,b):
return a-b
如果排序的元素是其他类型的,
你所定义的这个函数只需满足a逻辑小于b,函数返回负数;a逻辑等于b,函数返回0;a逻辑大于b,函数返回正数就行
cmp()函数本身在python2里是一个内置函数
cmp(42,32)
1
cmp(99,100)
-1
cmp(10,10)
0
————————————————
可参考:https://blog.csdn.net/robinson_/article/details/51484147
三、functools.cmp_to_key
python3 取消了cmp 参数,可以用functools.cmp_to_key 代替
import functools
nums=[3,30,34,5,9]
strs=[str(num) for num in nums]
strs.sort(key=functools.cmp_to_key(lambda x,y:int(x+y)-int(y+x)))
print(''.join(strs))
输出:3033459
比较函数
和键函数
的区别:
比较函数是任何接受两个参数并进行比较的可调用对象,小于返回负数,相等返回零,大于返回正数。
键函数是接受一个参数并返回另一个值作为排序键的可调用对象。