Practical Mapping Examples
Real-World Mapping Scenarios
Mapping functions are powerful tools in various programming tasks. This section explores practical applications across different domains.
1. Data Type Conversion
## Converting strings to integers
string_numbers = ['1', '2', '3', '4', '5']
integers = list(map(int, string_numbers))
## Result: [1, 2, 3, 4, 5]
## Converting temperatures
celsius = [0, 10, 20, 30, 40]
fahrenheit = list(map(lambda c: (c * 9/5) + 32, celsius))
## Result: [32.0, 50.0, 68.0, 86.0, 104.0]
2. Text Processing
## Cleaning and transforming text
names = [' john ', ' ALICE ', ' bob ']
cleaned_names = list(map(str.strip, map(str.lower, names)))
## Result: ['john', 'alice', 'bob']
## Filtering and mapping complex data
students = [
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 92},
{'name': 'Charlie', 'grade': 78}
]
## Extract names of students with grade > 80
high_performers = list(map(lambda x: x['name'],
filter(lambda x: x['grade'] > 80, students)))
## Result: ['Alice', 'Bob']
4. Numerical Operations
## Matrix operations
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
squared_matrix = list(map(lambda row: list(map(lambda x: x**2, row)), matrix))
## Result: [[1, 4, 9], [16, 25, 36], [49, 64, 81]]
Mapping Workflow Visualization
graph TD
A[Input Data] --> B[Mapping Function]
B --> C[Transformed Data]
C --> D{Further Processing}
Scenario |
Recommended Method |
Reason |
Small Lists |
List Comprehension |
Readability |
Large Datasets |
Generator Expression |
Memory Efficiency |
Complex Transformations |
map() with lambda |
Flexibility |
Advanced Mapping Techniques
Functional Programming Approach
## Functional composition
from functools import reduce
def compose(*functions):
return reduce(lambda f, g: lambda x: f(g(x)), functions)
## Chained transformations
process = compose(str.upper, str.strip)
names = [' python ', ' mapping ']
processed = list(map(process, names))
## Result: ['PYTHON', 'MAPPING']
Best Practices
- Choose the right mapping method for your specific use case
- Consider performance and readability
- Use type hints and docstrings for clarity
- Leverage functional programming concepts
By mastering these practical mapping techniques, you'll enhance your Python skills, a core focus of LabEx's advanced programming curriculum.