Advanced Sorting Strategies
Multi-Level Sorting Techniques
Tuple-Based Sorting
## Complex object sorting
students = [
('Alice', 85, 22),
('Bob', 75, 20),
('Charlie', 85, 21)
]
## Sort by grade (descending), then by age
sorted_students = sorted(students, key=lambda x: (-x[1], x[2]))
print(sorted_students)
Sorting with Multiple Criteria
Custom Comparison Functions
def custom_sort_key(item):
return (
-item['score'], ## Primary sort (descending)
item['name'] ## Secondary sort
)
data = [
{'name': 'Alice', 'score': 95},
{'name': 'Bob', 'score': 95},
{'name': 'Charlie', 'score': 85}
]
sorted_data = sorted(data, key=custom_sort_key)
Advanced Sorting Strategies Matrix
Strategy |
Use Case |
Complexity |
Performance |
Tuple Sorting |
Multi-level comparison |
Medium |
O(n log n) |
Custom Key Functions |
Complex object sorting |
High |
O(n log n) |
Partial Sorting |
Large datasets |
Low |
O(n + k log k) |
Partial and Efficient Sorting
## Partial sorting with heapq
import heapq
def partial_sort(iterable, k):
return heapq.nlargest(k, iterable)
numbers = [5, 2, 8, 1, 9, 3, 7]
top_3 = partial_sort(numbers, 3)
print(top_3) ## Output: [9, 8, 7]
Mermaid Sorting Strategy Flow
graph TD
A[Input Data] --> B{Sorting Strategy}
B --> |Simple Sorting| C[Basic Key Function]
B --> |Complex Sorting| D[Multi-Level Key]
B --> |Large Dataset| E[Partial Sorting]
C --> F[Sorted Result]
D --> F
E --> F
Caching Sort Keys
def cached_sort_key(item):
## Compute expensive key once
return item.expensive_calculation()
## Use functools.cache for memoization
from functools import cache
@cache
def expensive_key_calculation(item):
## Simulate complex computation
return complex_processing(item)
Handling Special Sorting Scenarios
Stable Sorting
## Maintain original order for equal elements
data = [(1, 'b'), (2, 'a'), (1, 'c')]
stable_sorted = sorted(data, key=lambda x: x[0])
print(stable_sorted)
Best Practices
- Choose the right sorting strategy
- Consider time and space complexity
- Use built-in Python sorting tools
At LabEx, we recommend mastering these advanced sorting techniques to write more efficient Python code.
- Minimize key function complexity
- Use built-in sorting methods
- Profile and optimize for specific use cases