
- 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 – Sort String list by K character frequency
When it is required to sort a list of strings based on the ‘K’ number of character frequency, the ‘sorted’ method, and the lambda function is used.
Example
Below is a demonstration of the same −
my_list = ['Hi', 'Will', 'Jack', 'Python', 'Bill', 'Mills', 'goodwill'] print("The list is : " ) print(my_list) my_list.sort() print("The list after sorting is ") print(my_list) K = 'l' print("The value of K is ") print(K) my_result = sorted(my_list, key = lambda ele: -ele.count(K)) print("The resultant list is : ") print(my_result)
Output
The list is : ['Hi', 'Will', 'Jack', 'Python', 'Bill', 'Mills', 'goodwill'] The list after sorting is ['Bill', 'Hi', 'Jack', 'Mills', 'Python', 'Will', 'goodwill'] The value of K is l The resultant list is : ['Bill', 'Mills', 'Will', 'goodwill', 'Hi', 'Jack', 'Python']
Explanation
A list of strings is defined, and is displayed on the console.
The list is sorted ascending order, and displayed on the console.
The value of ‘K’ is initialized and displayed on the console.
The list is sorted using the ‘sorted’ method, and the key is specified as the lambda function.
This is assigned to a variable which is displayed on the console.
- Related Articles
- Python - Sort rows by Frequency of K
- Python – Sort by Rear Character in Strings List
- Python – Sort by Uppercase Frequency
- Python – Sort Matrix by None frequency
- Frequency of each character in String in Python
- Python – Sort row by K multiples
- MySQL query to sort by certain last string character?
- Python – Sort given list of strings by numeric part of string
- Python – Character indices Mapping in String List
- List expansion by K in Python
- Check if frequency of character in one string is a factor or multiple of frequency of same character in other string in Python
- Sort String Array alphabetically by the initial character only in Java
- Python – Sort given list of strings by part the numeric part of string
- Python – Sort a List by Factor count
- How to sort a Python date string list?

Advertisements