- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Sort List items on basis of their Digits
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’.
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)
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]
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.
- Python – Sort List items on the basis of their Digits
- Sort the numbers according to their sum of digits in C++
- Program to update list items by their absolute values in Python
- Python program to Sort a List of Dictionaries by the Sum of their Values
- Program to sort out phrases based on their appearances in Python
- Python | Sum of number digits in List
- Select items based on value first, then order on the basis of date for rest of the records in MySQL
- Sort Tuples by Total digits in Python
- Python – Sort Tuples by Total digits
- Program to sort numbers based on 1 count in their binary representation in Python
- Python program to sort tuples by frequency of their absolute difference
- Convert list of tuples into digits in Python
- Python program to Sort Tuples by their Maximum element
- Extract digits from Tuple list Python
- Python | Sort the values of first list using second list