flatten a level one list

bonono at gmail.com bonono at gmail.com
Thu Jan 12 23:58:37 EST 2006


David Murmann wrote:
> Robin Becker schrieb:
> > # New attempts:
> > from itertools import imap
> > def flatten4(x, y):
> >     '''D Murman'''
> >     l = []
> >     list(imap(l.extend, izip(x, y)))
> >     return l
> >
> >
> > from Tkinter import _flatten
> > def flatten5(x, y):
> >     '''D Murman'''
> >     return list(_flatten(zip(x, y)))
>
> well, i would really like to take credit for these, but they're
> not mine ;) (credit goes to Michael Spencer). i especially like
> flatten4, even if its not as fast as the phenomenally faster
> flatten7.
>
Me too. And expand a bit on flatten4, I got this interesting result.

bonono at moresing:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s
"import itertools; a=zip(xrange(1000),xrange(1000))" "l=len(a);
li=[None]*l*2;li[::2]=range(1000); li[1::2]=range(1000)"
1000 loops, best of 3: 318 usec per loop

bonono at moresing:~/bonobo/psp$ python ~/lib/python2.4/timeit.py -s
"import itertools,psyco; a=zip(xrange(1000),xrange(1000));li=[]"
"filter(li.extend,a)"
1000 loops, best of 3: 474 usec per loop

Still 50% slower but it has the advantage that it works on all kinds of
sequence as they can be efficiently izip() together.




More information about the Python-list mailing list