convert list of tuples into several lists

Oliver Eichler oliver.eichler at dspsolutions.de
Thu Feb 10 04:35:03 EST 2005


Pierre Barbier de Reuille wrote:
> 
> Best answer is : try it :)
> use the "timeit" module (in the standard lib) to do so ...

Ok, (a second time. I hope the first post was cancelled as it was false)

import timeit

s = """\
a,b,c1,c2 = zip(*[(x[2],x[4], x[2]-x[1], x[2] - x[3]) for x in z])
"""

t = timeit.Timer(stmt=s,setup="z = [(1,2,3,4,5)]*1000")
print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)

s ="""\
a = []
b = []
c1 = []
c2 = []
for x in z:
  a.append(x[2])
  b.append(x[4])
  c1.append(x[2] - x[1])
  c2.append(x[2] - x[3])
"""

t = timeit.Timer(stmt=s,setup="z = [(1,2,3,4,5)]*1000")
print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000)

for 100 elements:
oeichler at frog:~/tmp> python test.py
104.67 usec/pass
180.19 usec/pass

for 1000 elements:
oeichler at frog:~/tmp> python test.py
1432.06 usec/pass
1768.58 usec/pass


What do we learn? The zip-thingy is even faster than the for loop

Learned my lesson :)

Thanks to all

Oliver




More information about the Python-list mailing list