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 – Filter Tuples with Strings of specific characters
When it is required to filter tuples with strings that have specific characters, a list comprehension and the all() function can be used to check if all characters in each string exist within a given character set.
Example
Below is a demonstration of filtering tuples containing only strings whose characters are present in a specific character set ?
my_list = [('pyt', 'best'), ('pyt', 'good'), ('fest', 'pyt')]
print("The list is :")
print(my_list)
char_string = 'pyestb'
my_result = [index for index in my_list if all(all(sub in char_string for sub in element) for element in index)]
print("The result is : ")
print(my_result)
Output
The list is :
[('pyt', 'best'), ('pyt', 'good'), ('fest', 'pyt')]
The result is :
[('pyt', 'best')]
How It Works
The filtering process works in nested steps:
For each tuple in the list, check every string within that tuple
For each string, verify that all its characters exist in the allowed character set
Only include tuples where all strings pass this character check
Step-by-Step Breakdown
my_list = [('pyt', 'best'), ('pyt', 'good'), ('fest', 'pyt')]
char_string = 'pyestb'
# Let's break down the filtering for each tuple
for i, tuple_item in enumerate(my_list):
print(f"Checking tuple {i}: {tuple_item}")
valid_tuple = True
for string_item in tuple_item:
string_valid = all(char in char_string for char in string_item)
print(f" String '{string_item}': {string_valid}")
if not string_valid:
valid_tuple = False
print(f" Tuple valid: {valid_tuple}\n")
Checking tuple 0: ('pyt', 'best')
String 'pyt': True
String 'best': True
Tuple valid: True
Checking tuple 1: ('pyt', 'good')
String 'pyt': True
String 'good': False
Tuple valid: False
Checking tuple 2: ('fest', 'pyt')
String 'fest': True
String 'pyt': True
Tuple valid: True
Alternative Approach
You can also use a regular function for better readability ?
def filter_tuples_by_chars(tuple_list, allowed_chars):
result = []
for tuple_item in tuple_list:
if all(all(char in allowed_chars for char in string) for string in tuple_item):
result.append(tuple_item)
return result
my_list = [('pyt', 'best'), ('pyt', 'good'), ('fest', 'pyt')]
char_string = 'pyestb'
filtered_tuples = filter_tuples_by_chars(my_list, char_string)
print("Filtered tuples:", filtered_tuples)
Filtered tuples: [('pyt', 'best'), ('fest', 'pyt')]
Conclusion
Use nested all() functions with list comprehension to filter tuples containing only strings whose characters exist in a specific character set. This approach provides an efficient way to validate character constraints across complex data structures.
