Sorting Lists

Tom Bryan tbryan at python.net
Tue Jul 24 22:04:39 EDT 2001


Nick Perkins wrote:


> 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.  
[...snip...]
> 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)

While it's probably much harder to read, one could 
avoid copying the list twice and maintain the semantics 
of sorting in place by doing something like the following...

def sort_by_field( index ):
    def cmpfunc( x, y, i=index ):
        return cmp( x[i], y[i] )
    return cmpfunc

data.sort( sort_by_field( 2 ) )

---Tom




More information about the Python-list mailing list