[prev in list] [next in list] [prev in thread] [next in thread]
List: python-list
Subject: Re: flatten(), [was Re: map/filter/reduce/lambda opinions ...]
From: Stian =?iso-8859-1?Q?S=F8iland?= <stian () soiland ! no>
Date: 2005-07-06 19:43:02
Message-ID: 20050706194302.GY12095 () itea ! ntnu ! no
[Download RAW message or body]
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]
--
http://mail.python.org/mailman/listinfo/python-list
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic