如何解决以特定格式对字符串或整数数组进行排序
我需要按以下形式对数组进行排序:
输入 [904,917,945,998,9,82,43,1112,99,97,93]
输出 [9,99,998,97,945,93,917,904,88,32,1112]
排序规则为(最大第一位,最大第二位,最大第三位,....),如果发生冲突,将保留较小的长度编号。
例如。在9和998中,第9位将排在第一位,因为第一位数字相同,但是位数较少。
如果我可以将逻辑作为键应用于Python的排序功能,那将很棒。
更新
我实际上是想在Leetcode上解决这个问题: https://leetcode.com/problems/largest-number/
要解决此问题,我需要对这种排序功能进行修改,以最终使用以下方法解决问题:
nums = [904,917,945,998,9,82,43,1112,99,97,93]
nums = [str(i) for i in nums]
n = max(map(len,nums))
nums = sorted(nums,key = lambda x : (x.ljust(n,x[0]),x[-1]),reverse=True)
解决方法
有点黑,但这是您要寻找的东西吗?
sorted(yourlist,key=lambda x: ''.join([str(9-int(y)) for y in str(x)]))
,
您可以定义一个名为spec_sort的函数:
def spec_sort(l):
l_str=map(str,l)
n=max(map(len,l_str))
return sorted(l,key=lambda i:(str(i).ljust(n,'a')),reverse=True)
这是示例:
i=[904,917,945,998,9,82,43,1112,99,97,93]
spec_sort(i)
输出应为:
[9,93,904,1112]