Open In App

Python – Specific Characters Frequency in String List

Last Updated : 13 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a String list, extract frequency of specific characters in the whole strings list.

Input : test_list = [“geeksforgeeks is best for geeks”], chr_list = [‘e’, ‘b’, ‘g’, ‘f’] 
Output : {‘g’: 3, ‘e’: 7, ‘b’: 1, ‘f’ : 2} 
Explanation : Frequency of certain characters extracted. 

Input : test_list = [“geeksforgeeks”], chr_list = [‘e’, ‘g’] 
Output : {‘g’: 2, ‘e’: 4} 
Explanation : Frequency of certain characters extracted.

Method #1 : Using join() + Counter()

In this, we concatenate all the strings, and then Counter() performs task of getting all frequencies. Last step is to get only specific characters from List in dictionary using dictionary comprehension.

Python3




# Python3 code to demonstrate working of
# Specific Characters Frequency in String List
# Using join() + Counter()
from collections import Counter
 
# initializing lists
test_list = ["geeksforgeeks is best for geeks"]
 
# printing original list
print("The original list : " + str(test_list))
 
# char list
chr_list = ['e', 'b', 'g']
 
# dict comprehension to retrieve on certain Frequencies
res = {key:val for key, val in dict(Counter("".join(test_list))).items() if key in chr_list}
     
# printing result
print("Specific Characters Frequencies : " + str(res))


Output

The original list : ['geeksforgeeks is best for geeks']
Specific Characters Frequencies : {'g': 3, 'e': 7, 'b': 1}

Time complexity: O(n), where n is the length of the input string.
Auxiliary space: O(k), where k is the number of characters in the character list (chr_list). 

Method #2 : Using chain.from_iterable() + Counter() + dictionary comprehension

In this, task of concatenation is done using chain.from_iterable() rather than join(). Rest all tasks are done as above method.

Python3




# Python3 code to demonstrate working of
# Specific Characters Frequency in String List
# Using chain.from_iterable() + Counter() + dictionary comprehension
from collections import Counter
from itertools import chain
 
# initializing lists
test_list = ["geeksforgeeks is best for geeks"]
 
# printing original list
print("The original list : " + str(test_list))
 
# char list
chr_list = ['e', 'b', 'g']
 
# dict comprehension to retrieve on certain Frequencies
# from_iterable to flatten / join
res = {key:val for key, val in dict(Counter(chain.from_iterable(test_list))).items() if key in chr_list}
     
# printing result
print("Specific Characters Frequencies : " + str(res))


Output

The original list : ['geeksforgeeks is best for geeks']
Specific Characters Frequencies : {'g': 3, 'e': 7, 'b': 1}

Time complexity: O(n), where n is the length of the input string
Auxiliary space: O(k), where k is the length of the character list.

Method #3: Using count() method.count() method returns the number of times a particular element occurs in a sequence.

Python3




# Python3 code to demonstrate working of
# Specific Characters Frequency in String List
 
# initializing lists
test_list = ["geeksforgeeks is best for geeks"]
 
# printing original list
print("The original list : " + str(test_list))
 
# char list
chr_list = ['e', 'b', 'g']
 
d=dict()
for i in chr_list:
    d[i]=test_list[0].count(i)
res=d
     
# printing result
print("Specific Characters Frequencies : " + str(res))


Output

The original list : ['geeksforgeeks is best for geeks']
Specific Characters Frequencies : {'e': 7, 'b': 1, 'g': 3}

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4: Using operator.countOf() method

Python3




# Python3 code to demonstrate working of
# Specific Characters Frequency in String List
import operator as op
# initializing lists
test_list = ["geeksforgeeks is best for geeks"]
 
# printing original list
print("The original list : " + str(test_list))
 
# char list
chr_list = ['e', 'b', 'g']
 
d=dict()
for i in chr_list:
    d[i]=op.countOf(test_list[0],i)
res=d
     
# printing result
print("Specific Characters Frequencies : " + str(res))


Output

The original list : ['geeksforgeeks is best for geeks']
Specific Characters Frequencies : {'e': 7, 'b': 1, 'g': 3}

Time Complexity: O(N), where n is the length of the given string
Auxiliary Space: O(N)

Method #5: Using loop and conditional statement

  • Initialize the list of strings test_list with a single string.
  • Print the original list test_list.
  • Initialize the list of characters chr_list whose frequency we want to count in the string.
  • Initialize an empty dictionary res to store the result.
  • Join all the strings in test_list into a single string using the join() method and store it in a variable joined_str.
  • Loop through each character in joined_str and count its frequency if it is present in the chr_list.
  • If a character is present in the chr_list and also present in the res dictionary, increment its count by 1. If a character is present in the chr_list but not in the res dictionary, add it to the dictionary with a count of 1.
  • Print the result dictionary res which will contain the frequencies of the specific characters in the original string.

Python3




# initializing lists
test_list = ["geeksforgeeks is best for geeks"]
 
# printing original list
print("The original list : " + str(test_list))
 
# char list
chr_list = ['e', 'b', 'g']
 
# initializing dictionary for result
res = {}
 
# loop through each character in the test_list and count their frequency
for char in "".join(test_list):
    if char in chr_list:
        if char in res:
            res[char] += 1
        else:
            res[char] = 1
             
# printing result
print("Specific Characters Frequencies : " + str(res))


Output

The original list : ['geeksforgeeks is best for geeks']
Specific Characters Frequencies : {'g': 3, 'e': 7, 'b': 1}

Time complexity: O(n), where n is the length of the string in the test_list. 
Auxiliary space: O(n), since the result dictionary will have at most n/3 key-value pairs if all the characters in the string are from the chr_list.



Similar Reads

Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
Given a string S, the task is to find the prefix of string S with the maximum possible length such that frequency of each character in the prefix is at most the number of characters in S with minimum frequency. Examples: Input: S = 'aabcdaab' Output: aabcd Explanation: Frequency of characters in the given string - {a: 4, b: 2, c: 1, d: 1} Minimum f
8 min read
Python program to check a string for specific characters
Here, will check a string for a specific character using different methods using Python. In the below given example a string 's' and char array 'arr', the task is to write a python program to check string s for characters in char array arr. Examples: Input: s = @geeksforgeeks% arr[] = {'o','e','%'}Output: [true,true,true] Input: s = $geek arr[] = {
4 min read
Python | Convert list of strings and characters to list of characters
Sometimes we come forward to the problem in which we receive a list that consists of strings and characters mixed and the task we need to perform is converting that mixed list to a list consisting entirely of characters. Let's discuss certain ways in which this is achieved. Method #1 : Using List comprehension In this method, we just consider each
6 min read
Python - Filter Tuples with Strings of specific characters
Given a Tuple List, extract tuples, which have strings made up of certain characters. Input : test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg')], char_str = 'gfestb' Output : [('gfg', 'best'), ('fest', 'gfg')] Explanation : All tuples contain characters from char_str. Input : test_list = [('gfg', 'best'), ('gfg', 'good'), ('fest', 'gfg
5 min read
Python - Specific case change in String List
While working with String lists, the problem of cases is common, but sometimes, we are concerned about changing cases in strings selectively. i.e. on the basis of another list. This can have applications in day-day programming. Let us discuss certain ways in which this task can be performed. Method #1 : Using loop + upper() + enumerate() This is on
7 min read
Python program to print k characters then skip k characters in a string
Given a String, extract K characters alternatively. Input : test_str = 'geeksgeeksisbestforgeeks', K = 4 Output : geekksisforg Explanation : Every 4th alternate range is sliced. Input : test_str = 'geeksgeeksisbest', K = 4 Output : geekksis Explanation : Every 4th alternate range is sliced. Method #1 : Using loop + slicing In this, we perform task
5 min read
Python | Consecutive characters frequency
Sometimes, while working with Python, we can have a problem in which we need to compute the frequency of consecutive characters till the character changes. This can have applications in many domains. Let us discuss certain ways in which this task can be performed in Python. Python Program to Count Consecutive Characters FrequencyUsing list comprehe
5 min read
Python - Odd Frequency Characters
Sometimes, while working with Python strings, we can have a problem in which we need to extract all the string characters which have odd number of occurrences. This problem can have applications in domains such as data domain and day-day programming. Let's discuss certain ways in which this task can be performed. Illustrations: Input : test_str = '
6 min read
Python - Successive Characters Frequency
Sometimes, while working with Python strings, we can have a problem in which we need to find the frequency of next character of a particular word in string. This is quite unique problem and has the potential for application in day-day programming and web development. Let's discuss certain ways in which this task can be performed. Input : test_str =
6 min read
Python - Remove front K characters from each string in String List
Sometimes, we come across an issue in which we require to delete the first K characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plus. Let’s discuss certain ways in which this can
6 min read
Practice Tags :
three90RightbarBannerImg