help with list comprehension

Yves Dorfsman yves at zioup.com
Thu May 1 23:01:10 EDT 2008


In the following script, m1() and m2() work fine. I am assuming m2() is 
faster although I haven't checked that (loops through the list twice instead 
of once).

Now what I am trying to do is something like m3(). As currently written it 
does not work, and I have tried different ways, but I haven't managed to 
make it work.

Is there a possibility ? Or is m2() the optimum ?


Thanks.



#!/usr/bin/python

l = [ { 'colour': 'black',   'num': 0},
       { 'colour': 'brown',   'num': 1},
       { 'colour': 'red',     'num': 2},
       { 'colour': 'orange',  'num': 3},
       { 'colour': 'yellow',  'num': 4},
       { 'colour': 'green',   'num': 5},
       { 'colour': 'blue',    'num': 6},
       { 'colour': 'violet',  'num': 7},
       { 'colour': 'grey',    'num': 8},
       { 'colour': 'white',   'num': 9}
     ]

def m1():
   colours = [ e['colour'] for e in l ]
   nums    = [ e['num']    for e in l ]

def m2():
   colours = []
   nums    = []
   for e in l:
     colours.append(e['colour'])
     nums.append(e['num'])

#def m3():
#  colours, nums = [ e['colour'], e['num'] for e in l ]





-- 
Yves.
http://www.SollerS.ca



More information about the Python-list mailing list