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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With