You are not logged in.
Hello all,
I have a a list of two lists, or 2 dimensional array for the C folks, and I would like to sort it based on the values of the second column. For example:
>>> print list
[["andrew", 10], ["alex", 18], ["john", 12]]
# the sorted list should look like this
>>> print sortedlist
[["alex", 18], ["john", 12], ["andrew", 10]]
Is there a function or method for doing this or should I wirte one myself? I have looked on the internet but have not found exactly what I want.
Thanks in advance,
baion
Last edited by baion baion (2010-04-09 10:04:22)
Offline
It should be easy to write it yourself. You might want to start here.
My Arch Linux Stuff • Forum Etiquette • Community Ethos - Arch is not for everyone
Offline
import operator
sorted(list, key=operator.itemgetter(1))
Offline
list.sort(lambda x, y: cmp(x[1], y[1]))
Offline
Xyne: That link is really helpful, I have figured it out.
Allan: This is almost what I wanted. What you propose does sort by the second column, but in ascending order, what I want is in descending order so I use
import operator
sorted(list, key=operator.itemgetter(1), reverse=True)
Ramses de Norre:
I get an error using your code saying
TypeError: must use keyword argument for key function
Perhaps it has to do with the fact that I am using Python 3?
Anyway, thank you people; problem solved.
Last edited by baion baion (2010-02-14 13:57:50)
Offline
Ramses de Norre:
I get an error using your code sayingTypeError: must use keyword argument for key function
Perhaps it has to do with the fact that I am using Python 3?
Indeed, it seems that the syntax I used has been removed in python3...
Offline