list sort question

Tim Peters tim_one at email.msn.com
Fri Oct 6 22:36:47 EDT 2000


[Bill Tolbert]
> I was asked today to sort a list of names and email addresses by last
> name. I ended up with a list of tuples:
>
> [('Bill Tolbert', 'bill_tolbert at bigfoot.com'), ('Tom Hogan',
> 'TH at bigfoot.com'), ('Test Zebra', 'tz at email.com'), ('Three Level Name',
> 'tln at email.com')]
>
> I couldn't figure out the list.sort(somefunction) syntax and resorted to
> all sorts of slicing before I gave up and solved it in a query (outside
> of Python).
>
> Any ideas on how to solve such a problem?

There's a sorting HowTo on python.org you should read.  It may have inspired
you to something like this:

def sortbylast(seq):
    from string import split
    augmented = []
    for name, email in seq:
        lastname = split(name)[-1]
        augmented.append((lastname, name, email))
    augmented.sort()
    answer = []
    for lastname, name, email in augmented:
        answer.append((name, email))
    return answer

print sortbylast([('Bill Tolbert', 'bill_tolbert at bigfoot.com'),
                  ('Tom Hogan','TH at bigfoot.com'),
                  ('Test Zebra', 'tz at email.com'),
                  ('Three Level Name','tln at email.com')])

which prints

[('Tom Hogan', 'TH at bigfoot.com'),
 ('Three Level Name', 'tln at email.com'),
 ('Bill Tolbert', 'bill_tolbert at bigfoot.com'),
 ('Test Zebra', 'tz at email.com')]

The list comprehesions feature new in Python 2.0 will make this approach
more compact, and, once you grok listcomps, clearer:

def sortbylast(seq):
    from string import split
    augmented = [(split(name)[-1], name, email)
                 for name, email in seq]
    augmented.sort()
    return [(name, email) for junk, name, email in augmented]

easily y'rs  - tim






More information about the Python-list mailing list