Complex Filtering Patterns
Advanced Filtering Techniques
List comprehensions can handle complex filtering scenarios beyond simple conditional statements. This section explores advanced techniques for sophisticated list manipulation.
Nested Comprehensions
Filtering Nested Lists
## Filter elements from nested lists
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_even_numbers = [num for row in matrix for num in row if num % 2 == 0]
print(flat_even_numbers) ## Output: [2, 4, 6, 8]
## Apply different transformations based on conditions
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
transformed = [num * 2 if num % 2 == 0 else num for num in numbers]
print(transformed) ## Output: [1, 4, 3, 8, 5, 12, 7, 16, 9, 20]
Complex Object Filtering
Filtering with Multiple Attributes
class Product:
def __init__(self, name, price, category):
self.name = name
self.price = price
self.category = category
products = [
Product('Laptop', 1000, 'Electronics'),
Product('Book', 20, 'Literature'),
Product('Smartphone', 500, 'Electronics')
]
expensive_electronics = [
product.name
for product in products
if product.category == 'Electronics' and product.price > 300
]
print(expensive_electronics) ## Output: ['Laptop', 'Smartphone']
Filtering Workflow
graph TD
A[Input Complex Data] --> B[Nested Iteration]
B --> C{Multiple Conditions}
C -->|Condition 1| D[Transformation 1]
C -->|Condition 2| E[Transformation 2]
D --> F[Create Filtered List]
E --> F
Advanced Filtering Strategies
Strategy |
Use Case |
Complexity |
Performance |
Nested Comprehension |
Multi-level Filtering |
High |
Moderate |
Conditional Transformation |
Dynamic Filtering |
Medium |
Good |
Object Attribute Filtering |
Complex Object Manipulation |
Medium |
Efficient |
Error Handling in Comprehensions
## Safe filtering with error handling
def safe_convert(value):
try:
return int(value)
except ValueError:
return None
mixed_data = ['1', '2', 'three', '4', 'five']
valid_numbers = [num for num in map(safe_convert, mixed_data) if num is not None]
print(valid_numbers) ## Output: [1, 2, 4]
- Avoid overly complex comprehensions
- Use generator expressions for large datasets
- Consider readability over extreme optimization
- Profile your code for performance-critical applications
Best Practices
- Keep comprehensions readable
- Break complex logic into multiple steps
- Use traditional loops for extremely complex filtering
- Leverage LabEx's Python learning resources for advanced techniques
By mastering these complex filtering patterns, you'll unlock powerful list manipulation capabilities in Python.