【Python】选择数组中的数,拼接成一个最大字符串数(易错题,cmp_to_key举例)

该博客介绍了如何通过Python的functools模块中的cmp_to_key方法,将一组整数字符串按特定规则排序以组合成最大的整数。通过定义xy_cmp函数比较两个数字的组合大小,然后对数字列表进行排序,最后将排序后的字符串连接成最大整数。示例中展示了如何处理包含928和9286的情况。
摘要由CSDN通过智能技术生成

题目

给定一组整数字符串,请拼出组合成最大整数。
例如:[33, 94, 928, 9286, 6, 71]

解答

字符 128 , 1286,拼成最大数,要把第二个数放在前面,也就是 1286128.
但是只要改动一个数字,928,9286,拼成最大数,应该把第一个数放在前面,也就是9289286.
为此,就要引入,两个参数。所以就用到了cmp_to_key这个方法。

from functools import cmp_to_key


li = [33, 94, 928, 9286, 6, 71]


def xy_cmp(x, y):
    # 如果返回的是一个大于0的值,那么代表a>b
    # 如果返回的是一个小于0的值,那么代表a<b
    # 如果返回的是一个等于0的值,那么代表a=b
    if x + y < y + x:
        return 1
    elif x+y > y+x:
        return -1
    else:
        return 0


def number_join(li):
    li = list(map(str, li))
    li.sort(key=cmp_to_key(xy_cmp))

    return "".join(li)


print(number_join(li))


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 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
发出的红包

打赏作者

夏2同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值