You are not logged in.

#1 2010-02-14 12:29:07

baion baion
Member
From: Nicosia, Cyprus
Registered: 2009-06-13
Posts: 48

[Solved] Sort a list of two lists by second column in python

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

#2 2010-02-14 12:58:40

Xyne
Administrator/PM
Registered: 2008-08-03
Posts: 6,963
Website

Re: [Solved] Sort a list of two lists by second column in python

It should be easy to write it yourself. You might want to start here.


My Arch Linux StuffForum EtiquetteCommunity Ethos - Arch is not for everyone

Offline

#3 2010-02-14 13:10:47

Allan
Pacman
From: Brisbane, AU
Registered: 2007-06-09
Posts: 11,365
Website

Re: [Solved] Sort a list of two lists by second column in python

import operator
sorted(list, key=operator.itemgetter(1))

Offline

#4 2010-02-14 13:22:22

Ramses de Norre
Member
From: Leuven - Belgium
Registered: 2007-03-27
Posts: 1,289

Re: [Solved] Sort a list of two lists by second column in python

list.sort(lambda x, y: cmp(x[1], y[1]))

Offline

#5 2010-02-14 13:56:11

baion baion
Member
From: Nicosia, Cyprus
Registered: 2009-06-13
Posts: 48

Re: [Solved] Sort a list of two lists by second column in python

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

#6 2010-02-14 14:13:24

Ramses de Norre
Member
From: Leuven - Belgium
Registered: 2007-03-27
Posts: 1,289

Re: [Solved] Sort a list of two lists by second column in python

baion baion wrote:

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?

Indeed, it seems that the syntax I used has been removed in python3...

Offline

Board footer

Powered by FluxBB