
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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.
Advertisements