Python3 sort和sorted用法+cmp_to_key()函数详解
作者:wiidi
这篇文章主要介绍了Python3 sort和sorted用法+cmp_to_key()函数详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
Python3 sort和sorted用法+cmp_to_key()函数

在python3中没有cmp函数
sort详情:

>>> a = [1,2,1,4,3,5] >>> a.sort() >>> a [1, 1, 2, 3, 4, 5] >>> a = [1,2,1,4,3,5] >>> sorted(a) #生成一个新的list,原来的list a 不变 [1, 1, 2, 3, 4, 5] >>> a [1, 2, 1, 4, 3, 5]
import sys
from functools import cmp_to_key
def cmp_new(x,y):
if (x+y)>(y+x):
return 1
elif (x+y)<(y+x):
return -1
else :
return 0
n=input()
s=input().split()
s.sort(key=cmp_to_key(cmp_new),reverse=True)
print(''.join(s).lstrip("0"))
#或者如下
s_new = sorted(s,cmp_to_key(cmp_new),reserve=True)
print(''.join(s_new).lstrip("0"))一句话理解cmp_to_key函数
主要是因为python3不支持比较函数,在一些接受key的函数中(例如sorted,min,max,heapq.nlargest,itertools.groupby),key仅仅支持一个参数,就无法实现两个参数之间的对比,采用cmp_to_key 函数,可以接受两个参数,将两个参数做处理,比如做和做差,转换成一个参数,就可以应用于key关键字之后。
举个例子
from functools import cmp_to_key L=[9,2,23,1,2] sorted(L,key=cmp_to_key(lambda x,y:y-x)) 输出: [23, 9, 2, 2, 1] sorted(L,key=cmp_to_key(lambda x,y:x-y)) 输出: [1, 2, 2, 9, 23]
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
