Python – Descending Sort String Numbers
Reverse Sorting a list is easy task and has been dealt with in many situations. With Machine Learning and Data Science emerging, sometimes we can get the data in the format of list of numbers but with string as data type. Generic Sort functions give erroneous result in that case, hence several other methods have to employed to perform these particular task. Lets discuss ways in which this is performed.
Method #1 : Naive Method In the naive method requires the type conversion of all the elements into integers of the list iterated through a loop. After that generic sort function is employed to perform the task. The descending sorting is done by passing reverse.
Python3
test_list = [ '4' , '6' , '7' , '2' , '1' ]
print ("The original list is : " + str (test_list))
for i in range ( 0 , len (test_list)) :
test_list[i] = int (test_list[i])
test_list.sort(reverse = True )
print ("The resultant reverse sorted list : " + str (test_list))
|
Output :
The original list is : ['4', '6', '7', '2', '1']
The resultant reverse sorted list : [7, 6, 4, 2, 1]
Time complexity: O(nlogn), where n is the length of the test_list.
Auxiliary Space: O(n), extra space of size n is required
Method #2 : Using sort() using key + reverse The generic sort() can be used to perform this particular task, but has to be specified with the key as integer to convert it to integer while performing sort function internally. The descending sorting is done by passing reverse.
Python3
test_list = [ '4' , '6' , '7' , '2' , '1' ]
print ("The original list is : " + str (test_list))
test_list.sort(key = int , reverse = True )
print ("The resultant reverse sorted list : " + str (test_list))
|
Output :
The original list is : ['4', '6', '7', '2', '1']
The resultant reverse sorted list : ['7', '6', '4', '2', '1']
Time Complexity: O(n*nlogn), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Last Updated :
09 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...