Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, functional programming, mapping to a higher level

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.

like image 234
Klaus Scheicher Avatar asked Aug 16 '13 08:08

Klaus Scheicher


1 Answers

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]]
like image 158
Eric Avatar answered Oct 20 '22 19:10

Eric