- 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
- Python – Sort Tuples by Total digits
- Sort the numbers according to their sum of digits in C++
- Python Pandas – How to select DataFrame rows on the basis of conditions
- Python program to Sort a List of Dictionaries by the Sum of their Values
- Python – Average digits count in a List
- Program to update list items by their absolute values in Python
- Python – Sort a List by Factor count
- Select items based on value first, then order on the basis of date for rest of the records in MySQL
- Python – Sort given list of strings by part the numeric part of string
- Program to sort out phrases based on their appearances in Python
- Python – Sort given list of strings by numeric part of string
- Python – Sort String list by K character frequency
- Python – Sort by Units Digit in a List
- Python – Sort by Rear Character in Strings List