help with list comprehension

Yves Dorfsman yves at zioup.com
Fri May 2 11:43:35 EDT 2008


George Sakkis wrote:

> Another alternative is:
> 
> from operator import itemgetter
> 
> def m3():
>     colours, nums = zip(*map(itemgetter('colour','num'), l))
> 
> It's slower than m1() but faster than m2(); it's also the most
> concise, especially if you extract more than two keys.

Good you guys gave me some ideas, I've made m3() work:

def m3()
   total = [ [e['colour'], e['num'], e['couleur']] for e in l ]
   c,d,e = zip(*total)
   return map(list, [c,d,e])

(I have to transform to lists, I need to transform them later on, so tuples 
won't work).

Unfortunately the timing is inconsistant, the first time I run
python -m timeit 'import listcomp ; listcomp.m1()'

m1 is the fastest. But then if I run the test several times, they all seem 
to be about the same time ; I'll have to try with a large list.

Now here is a question:
Is there any way to change my first line there for the list comp. to return 
a list of lists rather than a list of tuples ?



More information about the Python-list mailing list