Python – Sort String list by K character frequency

PythonServer Side ProgrammingProgramming

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.

raja
Published on 07-Sep-2021 09:10:06
Advertisements