flatten a level one list
Tim Hochberg
tim.hochberg at ieee.org
Wed Jan 11 22:38:35 EST 2006
Michael Spencer wrote:
> > Robin Becker schrieb:
> >> Is there some smart/fast way to flatten a level one list using the
> >> latest iterator/generator idioms.
> ...
>
> David Murmann wrote:
> > Some functions and timings
> ...
Here's one more that's quite fast using Psyco, but only average without it.
def flatten6():
n = min(len(xdata), len(ydata))
result = [None] * (2*n)
for i in xrange(n):
result[2*i] = xdata[i]
result[2*i+1] = ydata[i]
-tim
>
> Here are some more timings of David's functions, and a couple of additional
> contenders that time faster on my box (I don't have psyco):
>
> # From David Murman
> from itertools import izip
>
> xdata = range(1000)
> ydata = range(1000)[::-1]
>
> def flatten1(x, y):
> return [i for pair in izip(x, y) for i in pair]
>
> def flatten2(x, y):
> return [i for pair in zip(x, y) for i in pair]
>
> def flatten3(x, y):
> res = []
> for pair in izip(x, y):
> for i in pair:
> res.append(i)
> return res
>
>
> # New attempts:
> from itertools import imap
> def flatten4(x, y):
> l = []
> list(imap(l.extend, izip(x, y)))
> return l
>
>
> from Tkinter import _flatten
> def flatten5(x, y):
> return list(_flatten(zip(x, y)))
>
> flatten_funcs = [flatten1, flatten2, flatten3, flatten4, flatten5]
>
> def testthem():
> flatten1res = flatten_funcs[0](xdata, ydata)
> for func in flatten_funcs:
> assert func(xdata, ydata) == flatten1res
>
> def timethem():
> for func in flatten_funcs:
> print shell.timefunc(func, xdata, ydata)
>
> >>> testthem()
> >>> timethem()
> flatten1(...) 704 iterations, 0.71msec per call
> flatten2(...) 611 iterations, 0.82msec per call
> flatten3(...) 344 iterations, 1.46msec per call
> flatten4(...) 1286 iterations, 389.08usec per call
> flatten5(...) 1219 iterations, 410.24usec per call
> >>>
>
> Michael
>
More information about the Python-list
mailing list