Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > recursive map on nested list

Reply
Thread Tools

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

 
Reply With Quote
 
 
 
 
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

 
Reply With Quote
 
 
 
 
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 ]

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Recursive functions Vs Non-recursive functions - performance aspect vamsi C Programming 21 03-09-2009 10:53 PM
Two recursive calls inside of a recursive function n00m C++ 12 03-13-2008 03:18 PM
how to use recursive structure to build arbitrary levels' nested loop? so.intech C Programming 4 08-08-2006 11:09 PM
Recursive nested elements woe GR33DY XML 3 06-25-2004 09:55 PM
XSL Recursive nested elements woe GR33DY XML 0 06-24-2004 09:34 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57