python cmp_to_key
这里介绍一个Python 中比较好用的模块,就是functools中的cmp_to_key
这里所说的cmp_to_key是在python3中使用的,其实就是python2中的cmp函数
它具体的作用是什么呢?一句话就是比较函数
下面来举一个简单的例子就是:
class Solution:
def largestNumber(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
from functools import cmp_to_key
temp = list(map(str,nums))
temp.sort(key = cmp_to_key(lambda x,y:int(x+y)-int(y+x)),reverse = True )
return ''.join(temp if temp[0]!='0' else '0')
正如上面看到的,在python3中先要导入改模块即
from functools import cmp_to_key
它有两个传入参数x,y 当x>y时返回1 等于时返回0,否则返回-1
它在list中的工作机制就是将列表中的元素去两两比较,当cmp返回是正数时 交换两元素
以题目中的第一个例子来看,当按以上规则排完序后,列表中的元素10,2,又因为这里的
reverse = True
再一次将顺序颠倒过来2,10 正好就是我们想要的结果!!!!!!!!