Complex Mapping Scenarios
Nested List Mapping
## Transforming nested lists
nested_list = [[1, 2], [3, 4], [5, 6]]
flattened = list(map(lambda x: x[0] * x[1], nested_list))
print(flattened) ## Output: [2, 12, 30]
Mapping with Complex Data Structures
## Mapping dictionary values
users = [
{'name': 'Alice', 'age': 25},
{'name': 'Bob', 'age': 30}
]
names = list(map(lambda user: user['name'].upper(), users))
print(names) ## Output: ['ALICE', 'BOB']
Mapping Workflow Visualization
graph TD
A[Input Complex Data] --> B[Transformation Function]
B --> C[Mapped Results]
C --> D[Processed Output]
Functional Composition Mapping
Function Chaining
## Composing multiple transformations
def square(x):
return x ** 2
def add_ten(x):
return x + 10
numbers = [1, 2, 3, 4, 5]
transformed = list(map(lambda x: add_ten(square(x)), numbers))
print(transformed) ## Output: [11, 14, 19, 26, 35]
Mapping Techniques Complexity
Technique |
Complexity |
Use Case |
Simple Mapping |
Low |
Basic transformations |
Nested Mapping |
Medium |
Complex data structures |
Functional Composition |
High |
Advanced transformations |
Parallel Mapping with Multiple Conditions
## Advanced conditional mapping
def complex_transform(x):
if x % 2 == 0:
return x ** 2
elif x > 5:
return x + 10
else:
return x
numbers = [1, 2, 3, 4, 5, 6, 7]
result = list(map(complex_transform, numbers))
print(result) ## Output: [1, 4, 3, 16, 5, 36, 17]
Dynamic Function Mapping
## Mapping with dynamic function selection
def multiply_by_two(x):
return x * 2
def divide_by_three(x):
return x / 3
def select_function(index):
return multiply_by_two if index % 2 == 0 else divide_by_three
numbers = [1, 2, 3, 4, 5]
transformed = [select_function(i)(num) for i, num in enumerate(numbers)]
print(transformed) ## Output: [0.3333, 4, 1.0, 16, 1.6666]
- Use list comprehensions for better readability
- Leverage functional programming techniques
- Consider generator expressions for large datasets
Error-Resilient Mapping
## Robust mapping with error handling
def safe_process(x):
try:
return x ** 2 if isinstance(x, (int, float)) else None
except Exception:
return None
mixed_data = [1, 2, 'three', 4.5, [1, 2]]
result = list(map(safe_process, mixed_data))
print(result) ## Output: [1, 4, None, 20.25, None]
By understanding these complex mapping scenarios, you'll be able to handle sophisticated list transformations with confidence in your Python projects.