recursive map on nested list

A

alexandre_irrthum

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:
.... 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
 
B

bearophileHUGS

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
 
J

johnzenger

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 ]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top