Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3排序函数检查相同条件两次_Python_Sorting - Fatal编程技术网

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开始。这就意味着我们需要一个词典比较