

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- 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
- Python – Sort row by K multiples
- Frequency of each character in String in Python
- MySQL query to sort by certain last string character?
- List expansion by K in Python
- Sort Characters By Frequency in C++
- Sort by character length in MySQL
- Python – Sort given list of strings by numeric part of string
- Sort String Array alphabetically by the initial character only in Java
- Program to sort array by increasing frequency of elements in Python
- Python program to sort tuples by frequency of their absolute difference
- Python – Sort a List by Factor count
Advertisements