Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Sort by Maximum digit in Element
When it is required to sort by maximum digit in element, a method is defined that uses str() and max() method to determine the result. This technique converts each number to a string, finds its largest digit, and uses that digit as the sorting key.
Syntax
def max_digits(element):
return max(str(element))
list.sort(key=max_digits)
Example
Here's how to sort a list of numbers by their maximum digit ?
def max_digits(element):
return max(str(element))
my_list = [224, 192, 145, 18, 3721]
print("The list is :")
print(my_list)
my_list.sort(key=max_digits)
print("The result is :")
print(my_list)
The list is : [224, 192, 145, 18, 3721] The result is : [224, 145, 3721, 18, 192]
How It Works
The sorting works by comparing the maximum digits:
- 224 ? max digit is '4'
- 192 ? max digit is '9'
- 145 ? max digit is '5'
- 18 ? max digit is '8'
- 3721 ? max digit is '7'
Sorted order by max digit: '4' < '5' < '7' < '8' < '9'
Using Lambda Function
You can achieve the same result with a lambda function ?
numbers = [567, 834, 921, 456, 123]
print("Original list:", numbers)
sorted_list = sorted(numbers, key=lambda x: max(str(x)))
print("Sorted by max digit:", sorted_list)
Original list: [567, 834, 921, 456, 123] Sorted by max digit: [123, 456, 567, 834, 921]
Conclusion
Use max(str(element)) as a sorting key to order numbers by their largest digit. The str() function converts numbers to strings, allowing max() to find the highest character value.
Advertisements
