Given a list of non-negative numbers, the task is to sort these integers according to the sum of their digits.
Input : [12, 10, 106, 31, 15] Output : [10, 12, 31, 15, 106] Input : [1111, 19, 29, 11, 12, 9] Output : [11, 12, 1111, 9, 19, 29]
Let’s discuss few Pythonic ways to do this task.
Approach #1 : List comprehension
Using for loop to convert each element of list to a different list with its digits as elements. Now, use the sorted function with the above-mentioned function as key.
[10, 12, 31, 15, 106]
Approach #2 : Using
This approach is similar to the above approach with a slight difference that instead of for loop, we use
map() to convert each element of list to a different list with its digit as elements and then follow the similar approach as above.
[10, 12, 31, 15, 106]
There is also a one-liner alternative to the above mentioned approach.
- Python - Sort List items on basis of their Digits
- Python | Sort the values of first list using second list
- Python | Sort list of list by specified index
- Python | Sort list according to other list order
- Python | Sort Flatten list of list
- Python - Sort dictionaries list by Key's Value list index
- Python | Ways to sum list of lists and return sum list
- Minimize the sum calculated by repeatedly removing any two elements and inserting their sum to the Array
- Python | Sum of number digits in List
- Python | sort list of tuple based on sum
- Python Program for Odd-Even Sort / Brick Sort
- Python | Convert list of string to list of list
- Python | Convert list of tuples to list of list
- Python | Convert List of String List to String List
- Add elements in start to sort the array | Variation of Stalin Sort
- Python | Maximum sum of elements of list in a list of lists
- Python | Remove all digits from a list of strings
- Python | Convert list of tuples into digits
- Python | Checking if starting digits are similar in list
- Python | Remove element from given list containing specific digits
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.