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
Python 列表中最大的格式数字_Python_Sorting - Fatal编程技术网

Python 列表中最大的格式数字

Python 列表中最大的格式数字,python,sorting,Python,Sorting,问题: 给定一个非负整数列表,将它们排列成最大数 因此,给定[1,20,23,4,8],最大形成数为8423201 我无法理解以下解决方案: num.sort(cmp=lambda x,y:cmp(y+x,x+y))做什么 为什么它有两个参数x和y?如果输入一个列表,x和y在列表中代表什么 class Solution: # @param num, a list of integers # @return a string def largestNumber(self,

问题: 给定一个非负整数列表,将它们排列成最大数

因此,给定[1,20,23,4,8],最大形成数为8423201

我无法理解以下解决方案:

num.sort(cmp=lambda x,y:cmp(y+x,x+y))做什么

为什么它有两个参数x和y?如果输入一个列表,x和y在列表中代表什么

class Solution:
    # @param num, a list of integers
    # @return a string
    def largestNumber(self, num):
        num = [str(x) for x in num]
        num.sort(cmp=lambda x, y: cmp(y + x, x + y))
        largest = ''.join(num)
        return largest.lstrip('0') or '0'

if __name__ == "__main__":
    num = [3, 30, 34, 5, 9]
    print Solution().largestNumber(num) 

有人能解释一下代码解决方案吗?谢谢。

列表。排序(函数)
使用您指定的
函数对列表进行排序。

以下是代码的说明

class Solution:
    # @param num, a list of integers
    # @return a string
    def largestNumber(self, num):
        # converts list of numbers to list of strings
        num = [str(x) for x in num]
        # sorts list based on comparator function provided (an "anonymous" lambda function)
        # the comparator is used to compare pairs of elements for sorting (x comes first returns -1, "equal" returns 0, x comes after returns 1)
        # the lambda function takes two arguments x and y because comparator takes two arguments
        # since these are strings, they are compared by seeing which concatenation (+ operator with strings) 
        # comes "first" alphabetically but note the x and y are "swapped" from what you might expect (to reverse the sort)
        num.sort(cmp=lambda x, y: cmp(y + x, x + y))
        # join the sorted list together with empty string separators
        largest = ''.join(num)
        # remove any leading 0s
        return largest.lstrip('0') or '0'

if __name__ == "__main__":
    num = [3, 30, 34, 5, 9]
    print Solution().largestNumber(num) 

Python2.x排序函数允许使用
cmp
函数来比较两个项目
cmp(a,b)
如果ab,则返回1

此代码“创造性地”使用
cmp
,以获得解决问题所需的排序顺序;它将在“80”之前排序“8”,因为“880”大于“808”

问题是,您需要一个逆字母排序,但您希望短字符串先于长字符串(如果它们的前缀相同)

一个更通用的解决方案是按字母顺序反向排序,但用排序为“大于9”的字符将所有字符串右键填充到相同的长度,至少与正在排序的最长字符串一样长

我们如何选择这样一个角色?那么

ord("9")                                         # -> 57
print("".join(chr(ch) for ch in range(57, 75))   # "9:;<=>?@ABCDEFGHIJ"

FWIW,该代码将只在Python2上工作。使用
cmp
函数参数对
sort
进行排序已被弃用,并且在Python 3中不再存在。有关此问题的各种解决方案,请参阅。您可以在中的
sort
中阅读
cmp
的功能,请参见注释8。另请参阅内置的文档。这是使用旧式比较函数对列表进行排序,它使用字符串连接和比较进行排序,例如
'3'+'30'(330)>'30'+'3'(303)
,这将强制
'8'
到列表的前面,因为
“8XX”>“XX8”
def largest_number(nums):
    # convert to strings
    nums = [str(i) for i in nums]

    # find the length of the longest string
    longest = max(len(s) for s in nums)

    # create a function to pad strings to that length
    def padded(s, pad_char="A", length=longest):
        return s + pad_char * (length - len(s))

    # sort the strings greatest-to-least according to their padded values
    nums.sort(key=padded, reverse=True)
    # nums is now ["9", "5", "3", "34", "30"]

    # get the resulting output-string
    num = "".join(nums)

    # remove any leading 0s
    #  (this should only ever occur if all input nums were 0)
    num = num.lstrip("0")

    if num:
        return num
    else:
        # the string was all 0s - return a single 0
        return "0"

if __name__ == "__main__":
    nums = [3, 30, 34, 5, 9]
    print(largest_number(nums))   # -> "9533430"