flatten(), [was Re: map/filter/reduce/lambda opinions ...]
Ron Adam
rrr at ronadam.com
Tue Jul 5 18:50:30 EDT 2005
> Ok... How about a non-recursive flatten in place? ;-)
>
> def flatten(seq):
> i = 0
> while i!=len(seq):
> while isinstance(seq[i],list):
> seq.__setslice__(i,i+1,seq[i])
> i+=1
> return seq
>
> seq = [[1,2],[3],[],[4,[5,6]]]
> print flatten(seq)
>
> I think I'll be using the __setslice__ method more often.
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
More information about the Python-list
mailing list