sorting the list by inner elements

John Hunter jdhunter at ace.bsd.uchicago.edu
Wed Mar 24 08:33:02 EST 2004


>>>>> "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




More information about the Python-list mailing list