问题
How can I sort integers alphabetically? Like this:
integers = [10, 1, 101, 2, 111, 212, 100000, 22, 222, 112, 10101, 1100, 11, 0]
printed like this on Python console
[0, 1, 10, 100000, 101, 10101, 11, 1100, 111, 112, 2, 212, 22, 222]
I have tried this
def sort_integers(integers):
return sorted(integers)
but I guess you have to do it this way
def sort_integers(integers):
return sorted(integers, key = lambda....... )
I just don't know to what to write after the lambda?
回答1:
sorted(integers, key=str)
->
[0, 1, 10, 100000, 101, 10101, 11, 1100, 111, 112, 2, 212, 22, 222]
Explanation: str
is a function that casts the integers into strings. Since sorted
sorts strings alphabetically by default this does exactly what you asked for.
回答2:
You can simply use str
as key
:
sorted(integers,key=str)
So here for each element, the str
function is called, which converts the int
into a str
ing. That itself is not spectacular. But the comparison of strings is different: it sorts lexicographically.
>>> 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]
回答3:
If you want to sort your integers lexicographically as if they were strings, you can tell Python to treat them as strings while sorting:
>>> 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]
>>>
But you actually don't even have to have the lambda n: ...
part either. You can simply pass the str
function as the key
and Python will know what to do. calling str(n)
where n
is each element in your list:
>>> sorted(integers, key=str)
[0, 1, 10, 100000, 101, 10101, 11, 1100, 111, 112, 2, 212, 22, 222]
>>>
So your function would end up being:
def sort_integers(integers):
return sorted(integers, key=str)
回答4:
this will work
list(map(int, (sorted(str(i) for i in integers))))
output:
[0, 1, 10, 100000, 101, 10101, 11, 1100, 111, 112, 2, 212, 22, 222]
回答5:
Try a Most Significant Digit Radix Sort. This avoids having to convert the integers to strings, but is tougher to implement unless you use a library or other prewritten code.
来源:https://stackoverflow.com/questions/44835964/how-to-sort-integers-alphabetically