Velocity Reviews > recursive map on nested list

recursive map on nested list

alexandre_irrthum@yahoo.com
Guest
Posts: n/a

 03-21-2006
Hello,

I'd like to apply a function to elements of a nested list and wondered
if there is anything more idiomatic and/or shorter than this recursive
way:

>>> def recur_map(f, data):

.... if isinstance(data, list):
.... mapped_list = []
.... for i in data:
.... mapped_list.append(recur_map(f, i))
.... return mapped_list
.... else:
.... return f(data)
....
>>> recur_map(lambda x: x*2, [[1, 2], 3, 4, [5, 6, [7, 8]]])

[[2, 4], 6, 8, [10, 12, [14, 16]]]

Thanks,

alex

bearophileHUGS@lycos.com
Guest
Posts: n/a

 03-21-2006
I think for most purposes a program like this is short enough:

def recur_map2(fun, data):
if hasattr(data, "__iter__"):
return [recur_map2(fun, elem) for elem in data]
else:
return fun(data)

data = [set([1, 2]), [3], 4, [5, {6:4}, [7, 8]]]
print recur_map2(lambda x: x*2, data)

Bye,
bearophile

johnzenger@gmail.com
Guest
Posts: n/a

 03-21-2006
Uglier than yours, but down to two lines:

def recur_map(f, data):
return [ not hasattr(x, "__iter__") and f(x) or recur_map(f, x) for x
in data ]