Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort integers alphabetically

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?

like image 831
thomas Avatar asked Jun 29 '17 22:06

thomas


People also ask

Is sort ascending A to Z?

Ascending means going up, so an ascending sort will arrange numbers from smallest to largest and text from A to Z. Descending means going down, or largest to smallest for numbers and Z to A for text.


1 Answers

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.

like image 142
Johannes Avatar answered Oct 31 '22 20:10

Johannes