- 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 the basis of their Digits
When it is required to sort list items based on their digits, a method is defined that uses list comprehension and ‘sum’ method to determine the output.
Below is a demonstration of the same −
def sort_list_digit(my_list): digits = [int(digit) for digit in str(my_list) ] return sum(digits) my_list = [124, 20, 106, 35, 44] print("The list is :") print(my_list) print("The result is :") print(sorted(my_list, key = sort_list_digit))
The list is : [124, 20, 106, 35, 44] The result is : [20, 124, 106, 35, 44]
A method named ‘sort_list_digit’ is defined that takes a list as a parameter.
It uses list comprehension to iterate over the elements, and convert every element to an integer.
It then returns sum of the digits of the elements in the list as output.
Outside the method, a list of integers is defined and is displayed on the console.
The list is sorted and key is specified as the previously defined method.
This is the output that is displayed on the console.
- Python – Sort List items on basis of their Digits
- Sort the numbers according to their sum of digits in C++
- Python program to Sort a List of Dictionaries by the Sum of their Values
- Program to update list items by their absolute values in Python
- Select items based on value first, then order on the basis of date for rest of the records in MySQL
- Program to sort out phrases based on their appearances in Python
- Python | Sort the values of first list using second list
- Python - Create nested list containing values as the count of list items
- Python | Sum of number digits in List
- How to sort MySQL output on the basis of the column which is not in the result set?
- Python Pandas - Filtering columns from a DataFrame on the basis of sum
- How to sort the Processes based on their property name using PowerShell?
- How to randomize the items of a list in Python?
- Search records on the basis of date in MySQL?