Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Extract Strings with at least given number of characters from other list
When you need to extract strings that contain at least a specified number of characters from a given character list, list comprehension provides an efficient solution. This technique counts how many target characters appear in each string and filters based on a minimum threshold.
Example
Below is a demonstration of extracting strings with at least 2 characters from a specified character list ?
my_list = ["Python", "is", "fun", "to", "learn"]
print("The list is :")
print(my_list)
my_char_list = ['e', 't', 's', 'm', 'n']
my_key = 2
print("The value of key is")
print(my_key)
my_result = [element for element in my_list if sum(ch in my_char_list for ch in element) >= my_key]
print("The resultant list is :")
print(my_result)
Output
The list is : ['Python', 'is', 'fun', 'to', 'learn'] The value of key is 2 The resultant list is : ['Python', 'learn']
How It Works
The list comprehension uses a nested generator expression to count matching characters:
ch in my_char_list for ch in elementgenerates True/False for each charactersum()counts the True values (Python treats True as 1, False as 0)Only strings with count
>= my_keyare included in the result
Alternative Approach Using Filter
You can also use the filter() function for the same result ?
strings = ["Python", "is", "fun", "to", "learn"]
target_chars = ['e', 't', 's', 'm', 'n']
min_count = 2
def has_min_chars(word):
return sum(char in target_chars for char in word) >= min_count
result = list(filter(has_min_chars, strings))
print("Filtered strings:", result)
Filtered strings: ['Python', 'learn']
Conclusion
List comprehension with sum() provides a concise way to filter strings based on character count. This approach is both readable and efficient for extracting strings that meet specific character requirements.
