Python one-liner?

Evan Driscoll edriscoll at wisc.edu
Fri Apr 13 23:33:14 EDT 2012


I have a function 'f' and a list 'l'. I want a dictionary where the keys
are evaluations of 'f(thing from l)' and the values are lists of stuff
from 'l' that matches. So for instance, if 'f = lambda x: x%3' and
'l=range(9)', then I want { 0: [0,3,6], 1:[1,4,7], 2:[2,5,8]}.

I can do that with an explicit loop, or with this suggestion (untested)

    d = {}
    def appender(e):
        d.get(f(e), []).append(e)
    map(appender, l)

but I was wondering if there's some.... prettier way to do it with some
fancy dictionary comprehension or itertools expression or something. At
this point I'm asking mostly out of curiosity and less for some code to
actually use, so either Python 2 or 3 is acceptable (but I'm writing in
3 at the moment).

Evan


-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 552 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20120413/3374b754/attachment.sig>


More information about the Python-list mailing list