Practical Examples
Real-World Multilevel List Applications
1. Student Grade Management System
## Multilevel list for tracking student grades
students = [
['Alice', [85, 92, 78]],
['Bob', [76, 88, 90]],
['Charlie', [95, 87, 93]]
]
def calculate_average(student_data):
name, grades = student_data
avg = sum(grades) / len(grades)
return [name, avg]
student_averages = list(map(calculate_average, students))
print(student_averages)
2. Inventory Management
## Nested list for product inventory
inventory = [
['Electronics',
['Laptop', 50, 1200],
['Smartphone', 100, 800]
],
['Clothing',
['T-Shirt', 200, 25],
['Jeans', 150, 60]
]
]
def calculate_total_value(category):
total = sum(item[1] * item[2] for item in category[1:])
return [category[0], total]
inventory_value = list(map(calculate_total_value, inventory))
print(inventory_value)
## Transform nested list
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
squared_matrix = [[num**2 for num in row] for row in matrix]
print(squared_matrix)
Nested List Processing Strategies
Strategy |
Description |
Use Case |
Mapping |
Transform nested list elements |
Data preprocessing |
Filtering |
Select specific nested elements |
Data cleaning |
Reduction |
Aggregate nested list data |
Statistical analysis |
Nested List Processing Flow
graph TD
A[Input Nested List] --> B{Processing Strategy}
B --> |Mapping| C[Transform Elements]
B --> |Filtering| D[Select Elements]
B --> |Reduction| E[Aggregate Data]
C --> F[Output Transformed List]
D --> F
E --> F
3. Complex Data Aggregation
## Multi-level list data aggregation
sales_data = [
['North', [1200, 1500, 1800]],
['South', [900, 1100, 1300]],
['East', [1000, 1250, 1600]]
]
def region_performance(region_data):
region, sales = region_data
total_sales = sum(sales)
average_sales = total_sales / len(sales)
return [region, total_sales, average_sales]
performance_summary = list(map(region_performance, sales_data))
print(performance_summary)
Advanced Nested List Manipulation
## Flattening nested lists
def flatten(nested_list):
return [item for sublist in nested_list for item in sublist]
complex_list = [[1, 2], [3, 4], [5, 6]]
flat_list = flatten(complex_list)
print(flat_list)
LabEx encourages developers to practice these techniques to become proficient in handling multilevel lists, which are crucial for complex data processing tasks.