Python: sorting string numbers not lexicographically

I have an array of string-numbers, like:

numbers = ['10', '8', '918', '101010']

When I use sorted(numbers), I get them sorted lexicographically, e.g. '8' > '17'.

How can I iterate over the strings sorted according to the number value?


Solution 1:

You can use the built-in sorted() function with a key int to map each item in your list to an integer prior to comparison:

numbers = ['10', '8', '918', '101010']
numbers = sorted(numbers, key=int)
print(numbers)

Output

['8', '10', '918', '101010']

Using this method will output a list of strings as desired.

Solution 2:

You can transform the elements of the array to integers by using the built-in map function.

print sorted(map(int, numbers))

Output:

[8, 10, 918, 101010]

Solution 3:

If you want to keep as strings you can pass int as the key to list.sort which will sort the original list:

numbers = ['10', '8', '918', '101010']
numbers.sort(key=int)