recursive map on nested list

Discussion in 'Python' started by alexandre_irrthum@yahoo.com, Mar 21, 2006.

  1. Guest

    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
    , Mar 21, 2006
    #1
    1. Advertising

  2. Guest

    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
    , Mar 21, 2006
    #2
    1. Advertising

  3. Guest

    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 ]
    , Mar 21, 2006
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. GR33DY
    Replies:
    0
    Views:
    576
    GR33DY
    Jun 24, 2004
  2. GR33DY
    Replies:
    3
    Views:
    856
  3. jose luis fernandez diaz

    how to build a recursive map ?

    jose luis fernandez diaz, Apr 20, 2004, in forum: C++
    Replies:
    4
    Views:
    487
    Dan Cernat
    Apr 20, 2004
  4. n00m
    Replies:
    12
    Views:
    1,102
  5. vamsi
    Replies:
    21
    Views:
    2,050
    Keith Thompson
    Mar 9, 2009
Loading...

Share This Page