Python的cmp_to_key()函数详解

定义

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

剑指 Offer 45. 把数组排成最小的数

输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。

例 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)
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
The `functools.cmp_to_key` function is a utility function in Python's `functools` module that helps convert a comparison function to a key function. In Python, sorting a list of objects requires a way to compare the objects. This is done by providing a comparison function that takes two objects as input and returns `-1`, `0`, or `1` depending on whether the first object is less than, equal to, or greater than the second object. However, some sorting functions in Python (such as the `sorted` function) require a key function instead of a comparison function. A key function takes a single object as input and returns a value that can be used for sorting. The `cmp_to_key` function helps convert a comparison function to a key function by returning a new function that takes a single object as input and returns a tuple `(comparison_result, object)` where `comparison_result` is the result of calling the original comparison function with the input object and another object, and `object` is the input object itself. This tuple can then be used for sorting. Here's an example of how to use `cmp_to_key`: ``` from functools import cmp_to_key def compare_length(str1, str2): if len(str1) < len(str2): return -1 elif len(str1) > len(str2): return 1 else: return 0 strings = ['cat', 'dog', 'elephant', 'a', 'zebra'] sorted_strings = sorted(strings, key=cmp_to_key(compare_length)) print(sorted_strings) # Output: ['a', 'cat', 'dog', 'zebra', 'elephant'] ``` In this example, we define a comparison function `compare_length` that compares the lengths of two strings. We then use `cmp_to_key` to convert this comparison function to a key function, and pass it to the `sorted` function to sort a list of strings by length. The resulting sorted list is `['a', 'cat', 'dog', 'zebra', 'elephant']`.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值