sorting the list by inner elements
Thorsten Kampe
thorsten at thorstenkampe.de
Wed Apr 28 18:55:33 EDT 2004
Catching up old stuff...
* ketulp_baroda at yahoo.com (2004-03-24 15:43 +0100)
> I want to sort the list,the form of my list is
>
> name_city_list=[['jack','new york'],['mac','london'],['alice','paris']]
>
> all inner list has same format i.e first is name and second is city.
> now I want to sort it by the second element of the inner list(by city name).
>
> i.e after sorting my list should be like this
>
> name_city_list=[['mac','london'],['jack','new york'],['alice','paris']]
You need a general function sort:
def funcsort(seq, func):
""" sort seq by func(item) """
seq = seq[:]
seq.sort(lambda x, y: cmp(func(x), func(y)))
return seq
funcsort(name_city_list, lambda x: x[1])
More information about the Python-list
mailing list