Advanced Sorting Techniques
Custom Sorting with key
Parameter
The key
parameter allows complex and flexible sorting strategies by specifying a function to extract comparison keys.
Sorting by String Length
## Sorting strings by length
words = ['python', 'java', 'javascript', 'c++']
sorted_words = sorted(words, key=len)
print(sorted_words) ## Output: ['c++', 'java', 'python', 'javascript']
Multi-level Sorting
## Sorting complex objects with multiple criteria
students = [
{'name': 'Alice', 'grade': 85, 'age': 22},
{'name': 'Bob', 'grade': 85, 'age': 20},
{'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']))
for student in sorted_students:
print(student)
Sorting Workflow
graph TD
A[Sorting Process] --> B[Original List]
B --> C{Select Sorting Method}
C --> |Simple Sorting| D[sort() / sorted()]
C --> |Custom Sorting| E[key Parameter]
E --> F[Custom Comparison Function]
Advanced Sorting Techniques
Technique |
Description |
Use Case |
key Function |
Custom sorting logic |
Complex object sorting |
Lambda Functions |
Inline sorting methods |
Quick, simple transformations |
functools.cmp_to_key |
Legacy comparison functions |
Python 2.x compatibility |
Handling Complex Sorting Scenarios
Sorting with Multiple Conditions
## Sorting with multiple conditions
data = [
(3, 'apple'),
(1, 'banana'),
(3, 'cherry'),
(1, 'date')
]
## Sort by first element, then by second element
sorted_data = sorted(data)
print(sorted_data)
- Custom sorting with
key
has slight performance overhead
- Use simple key functions for better performance
- Avoid complex computations in sorting key
Practical Example: Sorting Dictionaries
## Sorting dictionary by values
inventory = {
'laptop': 1200,
'phone': 800,
'tablet': 500
}
## Sort by price
sorted_inventory = sorted(inventory.items(), key=lambda x: x[1])
for item, price in sorted_inventory:
print(f"{item}: ${price}")
Advanced Sorting Libraries
operator.itemgetter()
: Efficient key extraction
functools.cmp_to_key()
: Convert comparison functions
- Third-party libraries like
numpy
for specialized sorting
Learning with LabEx
At LabEx, we recommend practicing these advanced sorting techniques through interactive coding challenges to enhance your Python skills.