Real-world Applications
Data Analysis and Processing
Sorting Scientific Data
## Sorting experimental results
experiments = [
{'temperature': 25.5, 'reaction_rate': 0.75},
{'temperature': 30.2, 'reaction_rate': 0.82},
{'temperature': 20.1, 'reaction_rate': 0.68}
]
sorted_experiments = sorted(
experiments,
key=lambda x: (x['temperature'], x['reaction_rate'])
)
Financial Data Management
Stock Market Analysis
stocks = [
{'symbol': 'AAPL', 'price': 150.25, 'volume': 1000000},
{'symbol': 'GOOGL', 'price': 2500.75, 'volume': 500000},
{'symbol': 'MSFT', 'price': 300.50, 'volume': 750000}
]
## Sort by multiple criteria
sorted_stocks = sorted(
stocks,
key=lambda x: (-x['volume'], x['price'])
)
Log and Event Processing
Sorting System Logs
system_logs = [
{'timestamp': '2023-06-15 10:30:45', 'severity': 'ERROR'},
{'timestamp': '2023-06-15 09:15:22', 'severity': 'INFO'},
{'timestamp': '2023-06-15 11:45:10', 'severity': 'CRITICAL'}
]
sorted_logs = sorted(
system_logs,
key=lambda x: (x['severity'], x['timestamp'])
)
Workflow Visualization
graph TD
A[Raw Data] --> B[Apply Key Function]
B --> C[Sort Complex Structures]
C --> D[Processed Data]
D --> E[Analysis/Reporting]
Sorting Scenario |
Time Complexity |
Memory Usage |
Simple Lists |
O(n log n) |
Low |
Large Datasets |
O(n log n) |
Medium |
Complex Objects |
O(n log n) |
High |
Machine Learning Data Preparation
Preprocessing Training Data
ml_dataset = [
{'feature1': 0.5, 'feature2': 0.3, 'label': 1},
{'feature1': 0.2, 'feature2': 0.7, 'label': 0},
{'feature1': 0.8, 'feature2': 0.1, 'label': 1}
]
## Sort for consistent data processing
sorted_dataset = sorted(
ml_dataset,
key=lambda x: (x['label'], x['feature1'])
)
E-commerce Product Ranking
Sorting Product Recommendations
products = [
{'name': 'Laptop', 'price': 1000, 'rating': 4.5},
{'name': 'Smartphone', 'price': 800, 'rating': 4.7},
{'name': 'Tablet', 'price': 500, 'rating': 4.2}
]
## Advanced sorting for recommendations
sorted_products = sorted(
products,
key=lambda x: (-x['rating'], x['price'])
)
Network and Security Applications
IP Address Sorting
def ip_to_int(ip):
return int(''.join([bin(int(x)+256)[3:] for x in ip.split('.')]), 2)
ip_addresses = ['192.168.1.1', '10.0.0.1', '172.16.0.1']
sorted_ips = sorted(ip_addresses, key=ip_to_int)
By exploring these real-world applications, developers can leverage Python's powerful sorting capabilities to solve complex data organization challenges across various domains.