I have an arbitrarily nested iterable like so:
numbers = (1, 2, (3, (4, 5)), 7)
and I\'d like to map a function over it without changing the st
If you want to extend your result to dict
, set
and others, you can use Uriel's answer:
from collections import Collection, Mapping
def recursive_map(data, func):
apply = lambda x: recursive_map(x, func)
if isinstance(data, Mapping):
return type(data)({k: apply(v) for k, v in data.items()})
elif isinstance(data, Collection):
return type(data)(apply(v) for v in data)
else:
return func(data)
Tests input:
recursive_map({0: [1, {2, 2, 3}]}, str)
Yields:
{0: ['1', '{2, 3}']}