How to sort list

Michael J. Fromberger Michael.J.Fromberger at Clothing.Dartmouth.EDU
Wed Nov 22 01:37:27 CET 2006


In article <1164136547.137154.126740 at m73g2000cwd.googlegroups.com>,
 "Lad" <python at hope.cz> wrote:

> I have a list of emails and I would like to sorted that list by domains
> E.g.
> If the list is
> 
> Emails=['a at hotmail.com','a at yahoo.com','b at hotmail.com','c at yahoo.com',....]
> 
> after sorting I would like to have
> Emails=['a at hotmail.com','b at hotmail.com','a at yahoo.com','c at yahoo.com',....]
> 
> What is the best/easiest way?

One reasonable option is to use the .sort() method of a list:

  Emails.sort(key = lambda s: list(reversed(s.split('@'))))

The "key" parameter specifies how to obtain a sort key from each element 
in the source list.

Cheers,
-M

-- 
Michael J. Fromberger             | Lecturer, Dept. of Computer Science
http://www.dartmouth.edu/~sting/  | Dartmouth College, Hanover, NH, USA



More information about the Python-list mailing list