list sort question
Erik Max Francis
max at alcyone.com
Fri Oct 6 22:59:00 EDT 2000
Bill Tolbert wrote:
> 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'), ...]
>
> 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).
The function passed to sort takes two arguments, and must return -1, 0,
or 1 if the first is less than, equal to, or greater than the second
(respectively).
To get the last name of one of your tuples, you'd want something like
import string
tuple = ('Bill Tolbert', 'bill_tolbert at bigfoot.com')
string.split(tuple[0])[-1] # take the first element,
# split it into words,
# take the last word
So to sort the list you could do something like:
list.sort(lambda x, y: cmp(string.split(x[0])[-1],
string.split(y[0])[-1]))
Now this would be pretty unwieldy on anything but tiny lists. If you
are expecting to have even relatively sizeable lists, you'd probably
want to choose another data structure (another poster suggested a
dictionary whose keys are the last name and whose values are the
tuples).
--
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ Morality is a weakness of the mind.
\__/ Arthur Rimbaud
Esperanto reference / http://mirror/alcyone/max/lang/esperanto/
An Esperanto reference for English speakers.
More information about the Python-list
mailing list