如何按字母顺序排列整数



我如何按字母顺序排列整数?这样:

integers = [10, 1, 101, 2, 111, 212, 100000, 22, 222, 112, 10101, 1100, 11, 0]

在Python控制台上像这样打印

[0, 1, 10, 100000, 101, 10101, 11, 1100, 111, 112, 2, 212, 22, 222]

我尝试了这个

def sort_integers(integers):
    return sorted(integers)

,但我想你必须这样做

def sort_integers(integers):
    return sorted(integers, key = lambda....... )

我只是不知道在lambda之后要写什么?

sorted(integers, key=str)
->
[0, 1, 10, 100000, 101, 10101, 11, 1100, 111, 112, 2, 212, 22, 222]

说明:str是将整数铸成字符串的函数。由于 sorted默认按字母顺序排列字符串,这是您所要求的。

您可以简单地将str用作key

sorted(integers,key=str)

因此,对于每个元素,调用str函数,将int转换为str ING。那本身并不壮观。但是字符串的比较是不同的:它在词典上分类。

>>> sorted([0, 1, 10, 100000, 101, 10101, 11, 1100, 111, 112, 2, 212, 22, 222],key=str)
[0, 1, 10, 100000, 101, 10101, 11, 1100, 111, 112, 2, 212, 22, 222]

如果您想在整数上对整个词汇进行分类,就好像它们是字符串一样,您可以告诉Python在排序时将它们视为字符串:

>>> integers = [10, 1, 101, 2, 111, 212, 100000, 22, 222, 112, 10101, 1100, 11, 0]
>>> sorted(integers, key=lambda n: str(n))
[0, 1, 10, 100000, 101, 10101, 11, 1100, 111, 112, 2, 212, 22, 222]
>>> 

,但实际上您甚至不必拥有lambda n: ...零件。您可以将str函数传递为key,而Python知道该怎么做。调用 str(n)列表中的每个元素,其中 n

>>> sorted(integers, key=str)
[0, 1, 10, 100000, 101, 10101, 11, 1100, 111, 112, 2, 212, 22, 222]
>>>

,您的功能最终将成为:

def sort_integers(integers):
    return sorted(integers, key=str)

这将起作用

list(map(int, (sorted(str(i) for i in integers))))

输出:

[0, 1, 10, 100000, 101, 10101, 11, 1100, 111, 112, 2, 212, 22, 222]

尝试最重要的数字radix排序。这避免了必须将整数转换为字符串,但是除非您使用库或其他预编码代码,否则很难实施。

最新更新