Sorting email addresses by domain

Alex Martelli aleaxit at yahoo.com
Sun Nov 14 03:47:01 EST 2004


Jp Calderone <exarkun at divmod.com> wrote:
   ...
>   In Python 2.3,
> 
>     def key(addr):
>         parts = addr.split('@')
>         parts.reverse()
>         return parts
>     addresses.sort(lambda a, b: cmp(key(a), key(b)))

I'd prefer DSU...:

def key(addr): return addr.split('@', 1)[::-1]

aux = [ (key(a), a) for a in addresses ]
aux.sort()
addresses[:] = [ x for __, x in aux ]

if you do want to isolate 'key' into a function rather than expanding it
inline in the LC (and I do think that naming it helps).


>   In Python 2.4, re-using the above definition of key:
> 
>     addresses.sort(key=key)

Yep, that's equivalent to the 2.3's DSU.  The temptation to use a lambda
for the key is strong, of course, 'cuz 'key=' already does some 'naming'
and the whole construct is SO compact...:

    addresses.sort(key=lambda a: a.split('@', 1)[::-1])

but it seems to me that, again, a named function ends up clearer.


Alex



More information about the Python-list mailing list