定义
cmp_to_key() 使用键来比较元素
它内置在 functools 模块中,因此必须先导入 functools 才能使用该功能
与接受诸如 min()、max()、sorted() 等关键函数的工具一起使用。
只接受一个严格来说应该是可调用的参数
此函数返回可用于比较元素的特殊键
用于比较两个值并返回 1、-1 或 0
示例 1:
使用 cmp_to_key() 函数提供的键对列表进行排序的程序
import functools
def mycmp(a, b):
print("comparing ", a, " and ", b)
if a > b:
return 1
elif a < b:
return -1
else:
return 0
print(sorted([1, 2, 4, 2], key=functools.cmp_to_key(mycmp)))
输出:
comparing 2 and 1
comparing 4 and 2
comparing 2 and 4
comparing 2 and 2
comparing 2 and 4
[1, 2, 2, 4]
示例 2:
使用 cmp_to_key() 函数提供的键从列表中打印最大和最小数字的程序
import functools
def mycmp(a, b):
print("comparing ", a, " and ", b)
if a > b:
return 1
elif a < b:
return -1
else:
return 0
print(min([45, 78, 813], key=functools.cmp_to_key(mycmp)))
print(max([45, 78, 813], key=functools.cmp_to_key(mycmp)))
输出:
comparing 78 and 45
comparing 813 and 45
45
comparing 78 and 45
comparing 813 and 78
813
输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
例 1:
输入: [10,2]
输出: "102"
示例 2:
输入: [3,30,34,5,9]
输出: "3033459"
class Solution:
def minNumber(self, nums: List[int]) -> str:
def sort_rule(x, y):
a, b = x + y, y + x
if a > b: return 1
elif a < b: return -1
else: return 0
strs = [str(num) for num in nums]
strs.sort(key = functools.cmp_to_key(sort_rule))
return ''.join(strs)