Practical Mapping Examples
graph TD
A[Practical Mapping] --> B[Type Conversion]
A --> C[Data Cleaning]
A --> D[Mathematical Operations]
A --> E[String Manipulation]
1. Type Conversion
## Converting strings to integers
string_numbers = ['1', '2', '3', '4']
integers = list(map(int, string_numbers))
print(integers) ## Output: [1, 2, 3, 4]
## Mixed type conversion
mixed_data = ['10', '20.5', '30']
converted = list(map(float, mixed_data))
print(converted) ## Output: [10.0, 20.5, 30.0]
2. Data Cleaning and Normalization
## Removing whitespace from strings
names = [' Alice ', ' Bob ', ' Charlie ']
cleaned_names = list(map(str.strip, names))
print(cleaned_names) ## Output: ['Alice', 'Bob', 'Charlie']
## Lowercase conversion
mixed_case = ['Hello', 'WORLD', 'PyThOn']
lowercase = list(map(str.lower, mixed_case))
print(lowercase) ## Output: ['hello', 'world', 'python']
3. Mathematical Operations
## Complex mathematical transformations
def normalize(x, min_val, max_val):
return (x - min_val) / (max_val - min_val)
raw_data = [10, 20, 30, 40, 50]
normalized = list(map(normalize, raw_data,
[min(raw_data)]*len(raw_data),
[max(raw_data)]*len(raw_data)))
print(normalized) ## Normalized values between 0 and 1
4. String Manipulation
## Advanced string processing
def format_name(name):
return name.capitalize()
names = ['john', 'JANE', 'alice']
formatted = list(map(format_name, names))
print(formatted) ## Output: ['John', 'Jane', 'Alice']
Comparative Analysis
| Scenario |
map() |
List Comprehension |
Traditional Loop |
| Performance |
Efficient |
Moderate |
Slowest |
| Readability |
High |
High |
Low |
| Memory Usage |
Low |
Moderate |
High |
## Combining multiple transformations
def process_student(name, score):
return {
'name': name.capitalize(),
'score': score,
'passed': score >= 60
}
names = ['alice', 'bob', 'charlie']
scores = [75, 45, 65]
students = list(map(process_student, names, scores))
print(students)
## Output: [
## {'name': 'Alice', 'score': 75, 'passed': True},
## {'name': 'Bob', 'score': 45, 'passed': False},
## {'name': 'Charlie', 'score': 65, 'passed': True}
## ]
LabEx Recommendation
When mastering practical mapping techniques, LabEx offers interactive environments to practice and explore advanced mapping scenarios.
Best Practices
- Use
map() for uniform transformations
- Prefer list comprehensions for complex logic
- Convert map object to desired type
- Consider performance for large datasets