Sorting email addresses by domain

Greg Krohn greg at invalid.invalid
Wed Nov 10 21:53:00 EST 2004


Peter Murray wrote:
[snip]
> Anyway, I have a list of email address and I want to sort them by domain.
> List.sort() wont work as this looks at the start of each address only. So
> the answer I have come up with is to split each email address around the
> "@", swap the position of the name and domain, build a new list with these
> and then sort this. Then switch positions back, and join with an "@". It
> works, but it seems a little inelegant. Is there a better, or easier way to
> do this?
[snip code]

Elegant or Perlish, you decide:

addresses.sort(lambda a, b: cmp(a[a.find('@'):].lower(),
                                 b[b.find('@'):].lower()))

Note that this isn't case sensitive and items without an '@' will be 
placed at the end.

greg




More information about the Python-list mailing list