help with list comprehension

Karthik Gurusamy kar1107 at gmail.com
Fri May 2 01:11:09 EDT 2008


On May 1, 8:01 pm, Yves Dorfsman <y... at zioup.com> wrote:
> 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 ]
>

Looks like m1 is the cleanest; if you really want to run list-
comprehension once, one possible way:

>>> p = [ (e['colour'], e['num']) for e in l ]
>>> import operator
>>> map(operator.itemgetter(0), p)
['black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue',
'violet', 'grey', 'white']
>>> map(operator.itemgetter(1), p)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

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




More information about the Python-list mailing list