recursive map on nested list
alexandre_irrthum at yahoo.com
alexandre_irrthum at yahoo.com
Tue Mar 21 07:01:35 EST 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
More information about the Python-list
mailing list