Sorting Lists

Nick Perkins nperkins7 at home.com
Tue Jul 24 20:32:28 CEST 2001


"Colin Meeks" <colin at meeks.ca> wrote in message
news:lSh77.64029$2V.13507417 at news3.rdc1.on.home.com...
> I have a list that comprises of First Name, Surname, Age
> The list looks something like
>
>
[["Mickey","Mouse","50"],["Stan","Mantz","3"],["Junior","Wilst","40"],["Kim"
> ,"Bean","15"]]
>
> How can I sort the list to rearrange it by either First Name, Surname, Age
>
> I believe I'd have to use a cmpfunc in the sort, but not too sure how to
> achieve the above.
>
> Thanks
>
> Colin
>
>
> ---
> Outgoing mail is certified Virus Free.
> Checked by AVG anti-virus system (http://www.grisoft.com).
> Version: 6.0.265 / Virus Database: 137 - Release Date: 18/07/2001
>
>

You don't have to use a custom compare sort.
You can get what you want by creating a temp list, consisting of 'decorated'
values, and sorting that list.  These are actually tuples whose second
element is the real data, and the first element is a copy of the field that
you want to sort by.  (or a computed value, if you want)

So, if you want to sort by surname, for example,
you can transform each item like ["Mickey","Mouse","50"]
into ("Mouse",["Mickey","Mouse","50"]).
You use a regular sort on the list of transformed values,
then 'extract' your original values.

Here's an example of sorting records by a given field:

def sort_by_field(seq,index):
    tmp = [ (item[index],item) for item in seq ]
    tmp.sort()
    return [ item for (_,item) in tmp ]


data = [["Mickey","Mouse","50"],
        ["Stan","Mantz","3"],
        ["Junior","Wilst","40"],
        ["Kim","Bean","15"]]

data_by_lastname = sort_by_field(data,1)

print 'by last name:'
for record in data_by_lastname:
    print record

------
OUTPUT:

by last name:
['Kim', 'Bean', '15']
['Stan', 'Mantz', '3']
['Mickey', 'Mouse', '50']
['Junior', 'Wilst', '40']







More information about the Python-list mailing list