Python - Sort String list by K character frequency
Last Updated :
01 May, 2023
Given String list, perform sort operation on basis of frequency of particular character.
Input : test_list = ["geekforgeekss", "is", "bessst", "for", "geeks"], K = 's'
Output : ['bessst', 'geekforgeekss', 'geeks', 'is', 'for']
Explanation : bessst has 3 occurrence, geeksforgeekss has 3, and so on.
Input : test_list = ["geekforgeekss", "is", "bessst"], K = 'e'
Output : ["geekforgeekss", "bessst", "is"]
Explanation : Ordered decreasing order of 'e' count.
Method #1 : Using sorted() + count() + lambda
In this, sorted() is used to perform task of sort, count() is as function upon which sorting is to be performed. using additional key param, and function encapsulation used is lambda.
Python3
# Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using sorted() + count() + lambda
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 'e'
# "-" sign used to reverse sort
res = sorted(test_list, key = lambda ele: -ele.count(K))
# printing results
print("Sorted String : " + str(res))
OutputThe original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Sorted String : ['geekforgeeks', 'geeks', 'best', 'is', 'for']
Time Complexity: O(nlogn), where n is the length of the input list.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the list “test_list”.
Method #2 : Using sort() + count() + lambda
In this, we perform task of sort using sort(), this is similar to above, only difference being that sorting is done inplace.
Python3
# Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using sort() + count() + lambda
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 'e'
# "-" sign used to reverse sort
# inplace sort
test_list.sort(key = lambda ele: -ele.count(K))
# printing results
print("Sorted String : " + str(test_list))
OutputThe original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Sorted String : ['geekforgeeks', 'geeks', 'best', 'is', 'for']
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using operator.countOf() method
Python3
# Python3 code to demonstrate working of
# Sort String list by K character frequency
# Using operator.countOf()
import operator as op
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 'e'
# "-" sign used to reverse sort
res = sorted(test_list, key = lambda ele: -op.countOf(ele,K))
# printing results
print("Sorted String : " + str(res))
OutputThe original list is : ['geekforgeeks', 'is', 'best', 'for', 'geeks']
Sorted String : ['geekforgeeks', 'geeks', 'best', 'is', 'for']
Time Complexity: O(NLogN)
Auxiliary Space: O(N)
Method 4: Using heapq.nlargest() and count()
Step-by-step approach:
- Use the nlargest() function from the heapq module to return the n largest elements from a list of strings, sorted in descending order by the count of the target character K in each string. Set n to the length of the test_list to return all elements.
- Define a lambda function that takes a string as input and returns the count of the target character K in that string.
- Use the count() method to count the number of occurrences of K in each string in the test_list.
- Use the sorted() function to sort the test_list based on the count of K in each string. The key parameter of sorted() should be the lambda function defined in step 2.
- Return the sorted list of strings.
Python3
import heapq
# initializing list
test_list = ["geekforgeeks", "is", "best", "for", "geeks"]
# initializing K
K = 'e'
# define lambda function to count occurrences of K in a string
count_K = lambda s: s.count(K)
# use nlargest to sort test_list based on count of K in each string
n = len(test_list)
sorted_list = heapq.nlargest(n, test_list, key=count_K)
# use sorted to sort test_list based on count of K in each string
sorted_list = sorted(test_list, key=count_K, reverse=True)
# print results
print("Sorted String: ", sorted_list)
OutputSorted String: ['geekforgeeks', 'geeks', 'best', 'is', 'for']
Time complexity: O(n*log(n)) for sorting the list of strings.
Auxiliary space: O(n) for storing the list of strings.
Similar Reads
Python - Sort Strings by maximum frequency character
Given a string, the task is to write a Python program to perform sort by maximum occurring character. Input : test_list = ["geekforgeeks", "bettered", "for", "geeks"] Output : ['for', 'geeks', 'bettered', 'geekforgeeks'] Explanation : 1 < 2 < 3 < 4, is ordering of maximum character occurren
3 min read
Specific Characters Frequency in String List-Python
The task of counting the frequency of specific characters in a string list in Python involves determining how often certain characters appear across all strings in a given list.For example, given a string list ["geeksforgeeks"] and a target list ['e', 'g'], the output would count how many times 'e'
4 min read
Python - Sort by Rear Character in Strings List
Given a String list, perform sort by the rear character in the Strings list. Input : test_list = ['gfg', 'is', 'for', 'geeks'] Output : ['gfg', 'for', 'is', 'geeks'] Explanation : g < r < s = s, hence the order. Input : test_list = ['gfz', 'is', 'for', 'geeks'] Output : ['for', 'is', 'geeks',
5 min read
Python - Least Frequent Character in String
The task is to find the least frequent character in a string, we count how many times each character appears and pick the one with the lowest count.Using collections.CounterThe most efficient way to do this is by using collections.Counter which counts character frequencies in one go and makes it eas
3 min read
Maximum Frequency Character in String - Python
The task of finding the maximum frequency character in a string involves identifying the character that appears the most number of times. For example, in the string "hello world", the character 'l' appears the most frequently (3 times).Using collection.CounterCounter class from the collections modul
3 min read
Split String of list on K character in Python
In this article, we will explore various methods to split string of list on K character in Python. The simplest way to do is by using a loop and split().Using Loop and split()In this method, we'll iterate through each word in the list using for loop and split it based on given K character using spli
2 min read
Python | Remove Kth character from strings list
Sometimes, while working with data, we can have a problem in which we need to remove a particular column, i.e the Kth character from string list. String are immutable, hence removal just means re creating a string without the Kth character. Let's discuss certain ways in which this task can be perfor
7 min read
Python - Group list by first character of string
Sometimes, we have a use case in which we need to perform the grouping of strings by various factors, like first letter or any other factor. These types of problems are typical to database queries and hence can occur in web development while programming. This article focuses on one such grouping by
7 min read
Python | Alternate Sort in String list
Sometimes, while working with Python list, we can have a problem in which we need to perform sorting only of alternatively in list. This kind of application can come many times. Let's discuss certain way in which this task can be performed. Method : Using join() + enumerate() + generator expression
2 min read
Kth most frequent Character in a given String
Given a string str and an integer K, the task is to find the K-th most frequent character in the string. If there are multiple characters that can account as K-th most frequent character then, print any one of them.Examples: Input: str = "GeeksforGeeks", K = 3 Output: f Explanation: K = 3, here 'e'
6 min read