443,818 Members | 1,313 Online
Need help? Post your question and get tips & solutions from a community of 443,818 IT Pros & Developers. It's quick & easy.

# How to sort list

 P: n/a I have a list of emails and I would like to sorted that list by domains E.g. If the list is Emails=['a@hotmail.com','a@yahoo.com','b@hotmail.com','c@y ahoo.com',....] after sorting I would like to have Emails=['a@hotmail.com','b@hotmail.com','a@yahoo.com','c@y ahoo.com',....] What is the best/easiest way? Thank you for help L. Nov 21 '06 #1
7 Replies

 P: n/a Emails=['a@hotmail.com','a@yahoo.com','b@hotmail.com','c@y ahoo.com',....] after sorting I would like to have Emails=['a@hotmail.com','b@hotmail.com','a@yahoo.com','c@y ahoo.com',....] This problem isn't easy to solve in the general way, this is a first try: emails = ['a@hotmail.com','a@yahoo.com','b@hotmail.com','c@y ahoo.com'] print sorted(emails, key=lambda em: em.split("@")[::-1]) Bye, bearophile Nov 21 '06 #3

 P: n/a On Nov 21, 8:15 pm, "Lad" def compare(a, b): py a = a.split('@')[1] py b = b.split('@')[1] py return cmp(a, b) py> py>Emails = ['...@hotmail.com','...@yahoo.com','...@hotmail.com ','...@yahoo.com'] py>Emails.sort(compare) py>print Emails ['...@hotmail.com', '...@hotmail.com', '...@yahoo.com', '...@yahoo.com'] Nov 21 '06 #4

 P: n/a Lad 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@hotmail.com','a@yahoo.com','b@hotmail.com','c@y ahoo.com',....] after sorting I would like to have Emails=['a@hotmail.com','b@hotmail.com','a@yahoo.com','c@y ahoo.com',....] What is the best/easiest way? Thank you for help L. What have you tried? What issues did you have with your attempts? - Paddy. Nov 21 '06 #5

 P: n/a Klaus Alexander Seistrup wrote: Decorate-sort-undecorate? #v+ array = [] for addr in Emails: (user, domain) = addr.split('@') array.append((domain, user, addr)) # end for array.sort() SortedEmails = [addr for (user, domain, addr) in array] #v- note that DSU is built into Python these days: L.sort(key=transform) so you could use e.g. Emails.sort(key=lambda s: s.partition("@")[::-1]) also see: http://preview.tinyurl.com/yc3qak http://effbot.org/zone/python-list.htm#sorting Nov 22 '06 #6

 P: n/a Fredrik Lundh wrote: note that DSU is built into Python these days: L.sort(key=transform) Sweet, thanks for the hint. Cheers, -- Klaus Alexander Seistrup http://klaus.seistrup.dk/ Nov 22 '06 #7