问题: 给定一个非负数整数列表,将它们排列成最大数字。列表中最大的数字python
所以给出[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)
有人可以解释代码解决方案吗?谢谢。
FWIW,该代码将只对Python的2.使用'cmp'功能参数'sort'的工作已被弃用,在Python 3不再存在,看到的是https:/ /stackoverflow.com/questions/30140796/sort-a-list-to-form-the-largest-possible-number对这个问题的各种解决方案。您可以阅读[文档](https://docs.python.org/2/library/stdtypes.html#mutable-sequence-types)中的'sort'中的'cmp',请参阅注释8。 docs for the built-in ['cmp'](https://docs.python.org/2/library/functions.html#cmp)。 –
这是使用旧式比较函数来排序列表,它使用字符串连接和比较来排序,例如, ''3'+'30'(330)>'30'+'3'(303)',因为“8XX”>“XX8”'',所以会强制列表前面的'8'。 – AChampion