- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
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 list element as parameter and uses the ‘count’ and ‘str’ methods to determine the results.
Below is a demonstration of the same −
def sort_count_digits(elements): return str(elements).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)
The list is : [4522, 2452, 1233, 2465] The value of key is 2 The result is : [1233, 2465, 4522, 2452]
A method named ‘sort_count_digits‘ is defined that takes a list element as a parameter.
It converts the element into a string and gets the count of it.
This is returned as output.
A list is defined and displayed on the console.
The value for K is defined and is displayed on the console.
The list is sorted and the key is specified as the method which was previously defined.
This list is the output that is displayed on the console.
- Related Articles
- Python â€“ Sort by Units Digit in a List
- Count n digit numbers not having a particular digit in C++
- Python â€“ Sort by Maximum digit in Element
- Count of elements matching particular condition in Python
- Python â€“ Sort a List by Factor count
- Python â€“ Sort Matrix by Palindrome count
- Python program to Sort Strings by Punctuation count
- Python Program to sort rows of a matrix by custom element count
- Python â€“ Reform K digit elements
- Program to sort array by increasing frequency of elements in Python
- Count n digit numbers divisible by given number in C++
- Extract tuples having K digit elements in Python
- Digit Count in Range
- Python program to extract Mono-digit elements
- Python â€“ Sort Matrix by Number of elements greater than its previous element