When it is required to sort the elements of a list based on the digits, the ‘max’, ‘max’ method are used. We will also use the ‘sorted’ method, the ‘lambda’ function and ‘ljust’.
Example
Below is a demonstration of the same −
my_list = [4344, 2611, 122, 541, 33, 892, 48292, 460, 390, 120, 10, 2909, 11239, 1] print("The list is : " ) print(my_list) print("The list after sorting is : " ) my_list.sort() print(my_list) my_temp_val = map(str, my_list) my_max_length = max(map(len, my_temp_val)) my_result = sorted(my_list, key = lambda index : (str(index).ljust(my_max_length, 'a'))) print("The resultant list is : ") print(my_result)
Output
The list is : [4344, 2611, 122, 541, 33, 892, 48292, 460, 390, 120, 10, 2909, 11239, 1] The list after sorting is : [1, 10, 33, 120, 122, 390, 460, 541, 892, 2611, 2909, 4344, 11239, 48292] The resultant list is : [10, 11239, 120, 122, 1, 2611, 2909, 33, 390, 4344, 460, 48292, 541, 892]
Explanation
A list of strings is defined and is displayed on the console.
The list is sorted using a sort method and is displayed on the console.
The ‘map’ method is used to convert all elements in the list to a string.
This is assigned to a variable
The maximum of the elements in the list is found and assigned to a variable.
The sorted method is used to sort the list, and the key is the lambda function with the left justification.
This is assigned to a result.
This is displayed as output on the console.