flatten(), [was Re: map/filter/reduce/lambda opinions ...]

Stian Søiland stian at soiland.no
Wed Jul 6 15:43:02 EDT 2005


On 2005-07-06 00:50:30, Ron Adam wrote:

> This is probably the more correct way to do it. :-)
> 
> def flatten(seq):
>      i = 0
>      while i!=len(seq):
>          while isinstance(seq[i],list):
>              seq[i:i+1]=seq[i]
>          i+=1
>      return seq

Or what about a recursive generator?

    a = [1,2,[[3,4],5,6],7,8,[9],[],]

    def flatten(item):
        try:
            iterable = iter(item)
        except TypeError:
            yield item  # inner/final clause
        else:
            for elem in iterable:
                # yield_return flatten(elem)
                for x in flatten(elem):
                    yield x

    print list(flatten(a))


Of course, one of the problems here is that there is no way to
yield_return except to create yet another stupid-looking for-loop. This
is one of the flaws in the current generator functionallity of Python.

Using yield_return could also make it more obvious that the result is in
fact a generator in functions that wrap generators.

-- 
Stian Søiland               Work toward win-win situation. Win-lose
Trondheim, Norway           is where you win and the other lose.
http://soiland.no/          Lose-lose and lose-win are left as an
                            exercise to the reader.  [Limoncelli/Hogan]



More information about the Python-list mailing list