AmericanMade
AmericanMade

Reputation: 463

Sort list of ints by the first digit of each int

I'm trying to figure out how to sort a list of integers by the first digit in each int, (and if the same, move to the next digit, etc.)

I'm sure I can just loop through, (although I've been having issues because it seems like I need to make my list a list of strings in order to grab the first digit and this just hasn't been working out for me), but I'd like to know if there is a way to do this easily with the sorted() method.

EX:

myList = [34254, 2343, 49, 595, 323]

My desired result:

sortedList = [2343, 323, 34254, 49, 595]

Upvotes: 1

Views: 1515

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49320

Sort with a key of strings and you'll get ASCIIbetical sorting.

>>> myList = [34254, 2343, 49, 595, 323]
>>> sorted(myList, key=str)
[2343, 323, 34254, 49, 595]

Upvotes: 9

Related Questions