Python3排序函数检查相同条件两次
我想对数字数组进行排序,并以字符串格式返回最大的数字。 例如:Python3排序函数检查相同条件两次,python,sorting,Python,Sorting,我想对数字数组进行排序,并以字符串格式返回最大的数字。 例如: Array = [5,1,9,30] 应该回来 '95301' 我有以下代码来完成它 class LargestKey(str): def __lt__(x, y): print("x",x,"y",y, x+y > y+x) return x+y > y+x class Largest(): def largestNumber(self, nums): mapRe
Array = [5,1,9,30]
应该回来
'95301'
我有以下代码来完成它
class LargestKey(str):
def __lt__(x, y):
print("x",x,"y",y, x+y > y+x)
return x+y > y+x
class Largest():
def largestNumber(self, nums):
mapResult = map(str, nums)
num = ''.join(sorted(mapResult, key=LargestKey))
testNum = Largest()
print(testNum.largestNumber([5,1,9,30]))
根据最大键功能中的打印,输出为:
x 1 y 5 False
x 9 y 1 True
x 9 y 1 True
x 9 y 5 True
x 30 y 5 False
x 30 y 1 True
95301
我不明白为什么x=9和y=1的检查会发生两次30不是数组中最大的元素吗?我认为根据您的想法,它应该返回“30951”。基于示例,我假设这样做是为了排列数字,以便创建最大的可能输出数,在这种情况下,它确实应该从9开始。这就意味着我们需要一个词典比较