Advanced List Reordering
Custom Sorting with Complex Key Functions
Multi-Level Sorting
## Sorting with multiple criteria
students = [
{'name': 'Alice', 'grade': 85, 'age': 20},
{'name': 'Bob', 'grade': 85, 'age': 19},
{'name': 'Charlie', 'grade': 92, 'age': 21}
]
## Sort by grade (descending), then by age (ascending)
sorted_students = sorted(students, key=lambda x: (-x['grade'], x['age']))
Randomizing List Order
Using random.shuffle()
import random
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(numbers)
print(numbers) ## Output: Randomly reordered list
Advanced Reordering Techniques
Partitioning Lists
## Splitting list into groups
def partition(lst, condition):
return [x for x in lst if condition(x)], [x for x in lst if not condition(x)]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens, odds = partition(numbers, lambda x: x % 2 == 0)
Specialized Sorting Methods
Sorting with External Libraries
import numpy as np
## NumPy advanced sorting
arr = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5])
## Partial sort
partial_sorted = np.partition(arr, 3)
Reordering Strategies
Strategy |
Use Case |
Performance |
Complexity |
Built-in sort() |
Simple lists |
High |
Low |
sorted() |
Creating new sorted list |
Moderate |
Low |
Custom key sorting |
Complex sorting |
Moderate |
High |
NumPy sorting |
Numerical arrays |
Very High |
Moderate |
Visualization of Sorting Complexity
graph TD
A[Original List] --> B{Sorting Strategy}
B --> |Simple Sort| C[Basic Sorting]
B --> |Complex Sort| D[Advanced Reordering]
B --> |Performance Critical| E[Optimized Methods]
- Choose appropriate sorting method based on data size
- Use built-in methods for most common scenarios
- Leverage specialized libraries for complex operations
Advanced Reordering Techniques
Stable Sorting
## Maintaining original order of equal elements
data = [(1, 'b'), (2, 'a'), (1, 'a')]
stable_sorted = sorted(data, key=lambda x: x[0])
Key Takeaways
- Python offers flexible list reordering methods
- Custom sorting can be achieved through key functions
- Different strategies suit different use cases
- Performance varies with sorting approach