Is there a Python module that already does this?

Emile van Sebille emile at fenx.com
Wed Feb 6 21:46:51 EST 2002


"David Eppstein" <eppstein at ics.uci.edu> wrote in message
news:eppstein-80FFB2.17393106022002 at news.service.uci.edu...
> Here it is in a functional programming style:
>
> import operator
>
> def flatten(x):
>         if operator.isSequenceType(x) and (len(x) != 1 or x[0] != x):
>                 return reduce(operator.concat, map(flatten, x), [])
>         else:
>                 return [x]
>
> print flatten(["cat",5,['dog',[3,3,1]],"zoo"])
>
> ...outputs...
> ['c', 'a', 't', 5, 'd', 'o', 'g', 3, 3, 1, 'z', 'o', 'o']
>
> All that list copying makes it somewhat inefficient, though...

Why do you say that?  This looks pretty good to me.

You can squeeze out another (ugly) 15-20% performance gain
by making almost everything local and taking out the len check:

def flatten(x, isseq=operator.isSequenceType,
    concat=operator.concat, reduce=reduce, map=map):
    if isseq(x) and x[0] != x:
        return reduce(concat, map(flatten, x), [])
    else:
        return [x]

And when you make everything local, it's ugly beyond benefit.  ;-)

--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list