Complex Filtering Strategies
Advanced List Comprehension Techniques
List comprehensions can handle sophisticated filtering and transformation strategies beyond simple conditions, enabling powerful data manipulation techniques.
## Dynamic transformation based on conditions
numbers = range(10)
transformed = [x**2 if x % 2 == 0 else x**3 for x in numbers]
print(transformed)
## Output: [0, 1, 4, 27, 16, 125, 36, 343, 64, 729]
Nested Data Structure Filtering
## Complex filtering with nested dictionaries
products = [
{'name': 'Laptop', 'price': 1000, 'category': 'Electronics'},
{'name': 'Book', 'price': 20, 'category': 'Literature'},
{'name': 'Smartphone', 'price': 500, 'category': 'Electronics'}
]
expensive_electronics = [
product['name']
for product in products
if product['category'] == 'Electronics'
if product['price'] > 200
]
print(expensive_electronics) ## Output: ['Laptop', 'Smartphone']
Filtering with Custom Functions
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
primes = [x for x in range(50) if is_prime(x)]
print(primes)
Strategy Comparison
flowchart TD
A[Filtering Strategies] --> B[Simple Conditions]
A --> C[Nested Conditions]
A --> D[Function-Based Filtering]
A --> E[Conditional Transformations]
Strategy |
Readability |
Performance |
Complexity |
Simple Conditions |
High |
Best |
Low |
Nested Conditions |
Medium |
Good |
Medium |
Function-Based |
Low |
Variable |
High |
Conditional Transformations |
Medium |
Good |
Medium |
Advanced Filtering Patterns
## Multi-dimensional filtering
data = [
{'name': 'Alice', 'skills': ['Python', 'SQL'], 'experience': 3},
{'name': 'Bob', 'skills': ['Java', 'C++'], 'experience': 5},
{'name': 'Charlie', 'skills': ['Python', 'JavaScript'], 'experience': 2}
]
python_experts = [
person['name']
for person in data
if 'Python' in person['skills']
if person['experience'] > 2
]
print(python_experts) ## Output: ['Alice']
Handling Complex Scenarios
## Combining multiple filtering techniques
def is_valid_score(score):
return 70 <= score <= 90
exam_results = [
{'student': 'Alice', 'score': 85},
{'student': 'Bob', 'score': 65},
{'student': 'Charlie', 'score': 75}
]
qualified_students = [
result['student']
for result in exam_results
if is_valid_score(result['score'])
]
print(qualified_students) ## Output: ['Alice', 'Charlie']
Best Practices
- Prioritize readability
- Break complex logic into separate functions
- Use list comprehensions for clear, concise transformations
- Consider generator expressions for large datasets
LabEx recommends mastering these advanced filtering strategies to write more efficient and expressive Python code.