如何从列表的列表(List of Lists)或元组的列表(List of Tuples)中移除包含特定字符组合的元素
Solution for Filtering Lists/Tuples by Multiple Character Combinations
Problem Overview
You need to filter collections of lists or tuples to remove elements that meet specific criteria:
- Remove any element containing both
'b'and'd' - Extend this functionality to handle multiple forbidden combinations (e.g., remove elements with
'b'+'d'OR'e'+'f')
Approach
The core idea is to use set operations for efficient membership checks:
- Convert each element (list/tuple) into a set for quick lookups
- For each forbidden combination, check if all characters in the combination are present in the element's set
- Keep only elements that do NOT match any forbidden combination
Python Implementation
Here's a reusable function that works seamlessly for both lists of lists and lists of tuples:
def filter_forbidden_combinations(input_collection, forbidden_combinations): # Convert forbidden combinations to sets for consistent checks forbidden_sets = [set(comb) for comb in forbidden_combinations] filtered_results = [] for item in input_collection: item_set = set(item) # Check if the item contains all characters from any forbidden set should_remove = any(comb_set.issubset(item_set) for comb_set in forbidden_sets) if not should_remove: filtered_results.append(item) return filtered_results
Test Case 1: Single Forbidden Combination (b + d)
Inputs
- List of lists:
[['b'],['d'],['e'], ['b','d','e'],['b','e'],['e','f'],['b','d']] - List of tuples:
[('b',),('d',),('e'),('b','d','e'),('b','e'),('e','f'),('b','d')] - Forbidden combination:
[['b','d']]
Outputs
# Filtered list of lists [['b'], ['d'], ['e'], ['b','e'], ['e','f']] # Filtered list of tuples [('b',), ('d',), 'e', ('b','d','e'), ('b','e'), ('e','f')]
(Note: The standalone 'e' in the tuple list is handled correctly since set('e') creates the set {'e'})
Test Case 2: Multiple Forbidden Combinations (b+d AND e+f)
Input
Forbidden combinations: [['b','d'], ['e','f']]
Outputs
# Filtered list of lists [['b'], ['d'], ['e'], ['b','e']] # Filtered list of tuples [('b',), ('d',), 'e', ('b','d','e'), ('b','e')]
Key Notes
- Efficiency: Using sets ensures membership checks are O(1), making the function fast even for large collections
- Flexibility: Works with any iterable element (lists, tuples, strings) as long as forbidden combinations are iterables of characters
- Preservation: The original element type (list/tuple/string) is kept intact in the filtered output
内容的提问来源于stack exchange,提问作者Vignesh Ramasamy
相关产品推荐
相关产品推荐

