Re: map/filter/reduce/lambda opinions and background unscientific mini-survey
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.python archive

Re: map/filter/reduce/lambda opinions and background unscientific mini-survey

From: Ron Adam <rrr@ronadam.com>
Date: Mon Jul 04 2005 - 23:46:00 CEST

George Sakkis wrote:

> And finally for recursive flattening:
>
> def flatten(seq):
> return reduce(_accum, seq, [])
>
> def _accum(seq, x):
> if isinstance(x,list):
> seq.extend(flatten(x))
> else:
> seq.append(x)
> return seq
>
>
>>>>flatten(seq)
>
> [1, 2, 3, 4, 5, 6]
>
>
> George
>

How about this for a non recursive flatten.

def flatten(seq):
     s = []
     while seq:
         while isinstance(seq[0],list):
             seq = seq[0]+seq[1:]
         s.append(seq.pop(0))
     return s

seq = [[1,2],[3],[],[4,[5,6]]]
flatten(seq)

Ron
Received on Thu Sep 29 16:45:24 2005