Does anybody know how to map in Python easily a function to a higher level in a nested list, i.e. the equivalent to Map[f, expr, levelspec]
in Mathematica.
You can trivially roll your own
def map_level(f, item, level):
if level == 0:
return f(item)
else:
return [map_level(f, i, level - 1) for i in item]
>>> double = lambda x: x * 2
>>> data = [[1, 2, 3], [4, 5, 6]]
>>> map_level(double, data, 0)
[[1, 2, 3], [4, 5, 6], [1, 2, 3], [4, 5, 6]]
>>> map_level(double, data, 1)
[[1, 2, 3, 1, 2, 3], [4, 5, 6, 4, 5, 6]]
>>> map_level(double, data, 2)
[[2, 4, 6], [8, 10, 12]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With