Python - Sort by a particular digit count in elements

Python - Sort by a particular digit count in elements

In this tutorial, we'll sort a list of numbers based on the count of a particular digit in their decimal representation.

Scenario:

Let's say we have a list nums = [121, 131, 141, 151, 12321], and we want to sort these numbers based on the count of the digit 1 in them.

Expected output (for sorting by count of digit 1):

[141, 151, 131, 121, 12321] 

Steps:

  1. Define a function that counts the occurrences of a specific digit in a number.
  2. Use this function as a key to the sorted function to sort the list.

Code:

Let's implement the above steps:

def count_digit(num, digit): """Count occurrences of a specific digit in a number.""" return str(num).count(str(digit)) def sort_by_digit_count(nums, digit): """Sort a list of numbers by the count of a specific digit in them.""" return sorted(nums, key=lambda x: count_digit(x, digit)) # Test nums = [121, 131, 141, 151, 12321] sorted_nums = sort_by_digit_count(nums, 1) print(sorted_nums) # Output: [141, 151, 131, 121, 12321] 

Note:

In the above code, we used the str function to convert numbers to strings. This allows us to count the occurrences of a specific digit easily. The lambda function in the sorted call uses this count to determine the sort order of the numbers.

Summary:

In this tutorial, we learned how to sort a list of numbers based on the count of a particular digit in their decimal representation. This technique can be easily adapted to sort based on other criteria related to the digits in numbers.


More Tags

advanced-custom-fields negative-number ios camera rightbarbuttonitem tortoisesvn cmsamplebufferref combinatorics floating-point jmeter

More Programming Guides

Other Guides

More Programming Examples