Skip to content
Minsing Log
Go back

English Edition

How to Map a Func to Elements of Multiple Nested Data Structures

Programming & CS

Create nest_map

def nested_map(struct, map_fn):
	if isinstance(struct, tuple):
		return tuple(nested_map(x, map_fn) for x in struct)
	if isinstance(struct, list):
		return [nested_map(x, map_fn) for x in struct]
	if isinstance(struct, dict):
		return {k: nested_map(v, map_fn) for k, v in struct.items()}
	return map_fn(struct)

Follow the journey

Get new posts by email.

Short, honest notes on building, startups, learning, failures, and retrospectives, for readers who follow the journey rather than pass through from search.

The newsletter is coming soon. Until then, follow via RSS or email me to get notified.


Share this post:

Comments

Sign in with GitHub to leave a comment.


Previous Post
Python getter → What Is __getitem__?
Next Post
Stack -> Finding the Minimum Value