-4

I have list of numbers which is in the form of string and I want to sort the numbers in it. How do I sort such numbers in python?

Here is my list.

key_s=['115', '114', '117', '116', '111', '110', '113', '112', '68', '119', '118', '44', '45', '42', '43', '41', '76', '108', '109', '71', '107', '79', '13', '15', '14', '17', '16', '37']

I tried using key_s.sort().It returns None instead of sorted array. I even tried sorted(key_s) which is even not working. So what is the solution to sort it?

1 Answers1

4

Yes, list.sort() sorts in place, and returns None to indicate it is the list itself that has been sorted. The sorted() function returns a new sorted list, leaving the original list unchanged.

Use int as a key:

sorted(key_s, key=int)

This returns a new list, sorted by the numeric value of each string, but leaving the type of the values themselves unchanged.

Without a key, strings are sorted lexicographically instead, comparing character by character. Thus '9' is sorted after '10', because the character '1' comes before '9' in character sets, just like 'a' comes before 'z'.

The key argument lets you apply a Schwartzian_transform, informing the sorting algorithm what to sort by. Each value in the list is sorted according to key(value) (so int(value) here) instead of the original value itself.

Demo:

>>> key_s = ['115', '114', '117', '116', '111', '110', '113', '112', '68', '119', '118', '44', '45', '42', '43', '41', '76', '108', '109', '71', '107', '79', '13', '15', '14', '17', '16', '37']
>>> sorted(key_s, key=int)
['13', '14', '15', '16', '17', '37', '41', '42', '43', '44', '45', '68', '71', '76', '79', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119']
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343