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 a particular digit count in elements
When it is required to sort by a particular digit count in elements, a method is defined that takes a list element as parameter and uses the count() and str() methods to determine the results.
Below is a demonstration of the same ?
Example
def sort_count_digits(element):
return str(element).count(str(my_key))
my_list = [4522, 2452, 1233, 2465]
print("The list is :")
print(my_list)
my_key = 2
print("The value of key is")
print(my_key)
my_list.sort(key=sort_count_digits)
print("The result is :")
print(my_list)
Output
The list is : [4522, 2452, 1233, 2465] The value of key is 2 The result is : [1233, 2465, 4522, 2452]
How It Works
The sorting function counts how many times the digit 2 appears in each number:
1233: Contains 0 occurrences of digit 2
2465: Contains 1 occurrence of digit 2
4522: Contains 2 occurrences of digit 2
2452: Contains 2 occurrences of digit 2
The list is sorted in ascending order based on these counts.
Alternative Approach Using Lambda
numbers = [4522, 2452, 1233, 2465]
target_digit = 2
# Using lambda function for cleaner code
sorted_numbers = sorted(numbers, key=lambda x: str(x).count(str(target_digit)))
print("Original list:", numbers)
print("Sorted by digit count:", sorted_numbers)
Original list: [4522, 2452, 1233, 2465] Sorted by digit count: [1233, 2465, 4522, 2452]
Sorting by Multiple Digits
def count_specific_digits(number, digits):
"""Count occurrences of multiple digits in a number"""
num_str = str(number)
total_count = 0
for digit in digits:
total_count += num_str.count(str(digit))
return total_count
numbers = [1234, 2255, 3456, 2222]
target_digits = [2, 5]
sorted_numbers = sorted(numbers, key=lambda x: count_specific_digits(x, target_digits))
print("Numbers:", numbers)
print("Sorted by count of digits 2 and 5:", sorted_numbers)
Numbers: [1234, 2255, 3456, 2222] Sorted by count of digits 2 and 5: [1234, 3456, 2255, 2222]
Conclusion
Use the count() method on string representation of numbers to sort by digit frequency. Lambda functions provide a cleaner syntax for simple sorting operations.
Advertisements
