sorting the list by inner elements

ketulp_baroda at yahoo.com ketulp_baroda at yahoo.com
Thu Mar 25 07:59:55 EST 2004


John Hunter <jdhunter at ace.bsd.uchicago.edu> wrote in message news:<mailman.336.1080136535.742.python-list at python.org>...
> >>>>> "ketulp" == ketulp baroda <ketulp_baroda at yahoo.com> writes:
> 
>     ketulp> Hi, all I want to sort the list,the form of my list is
> 
>     ketulp>   name_city_list=[['jack','new
>     ketulp> york'],['mac','london'],['alice','paris']]
> 
>     ketulp> all inner list has same format i.e first is name and
>     ketulp> second is city.  now I want to sort it by the second
>     ketulp> element of the inner list(by city name).
> 
>     ketulp> i.e after sorting my list should be like this
> 
> The usual way is to simply reverse the tuple, sort, and then reverse
> back
> 
>   tmp = [ (city, name) for name, city in name_city_list]
>   tmp.sort()
>   name_city_list = [ (name, city) for city, name in tmp]
> 
> This is usually faster than writing a custom comparison func for sort.
> 
> JDH

Hi, John

I like ur idea but this will work for only when inner list has only
two elements. if inner list has five elements and i want to sort the
whole list by 3rd element then how can i do this ?

need ur help,
regards



More information about the Python-list mailing list