473,326 Members | 2,133 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Is there an easy way to sort a list by two criteria?

Hello!
I am a newbie in Python. Recently, I get stuck with the problem of
sorting by two criteria. In brief, I have a two-dimensional list (for
a table or a matrix). Now, I need to sort by two columns, but I cannot
figure out how to do that. I read somewhere that it is possible to do:
>>table.sort().sort()
but it does not work.
Can anyone help me with this?
PS: I am using Python under Ubuntu 6.06.

Best,
PM
Feb 10 '08 #1
5 7785
neocortex wrote:
Hello!
I am a newbie in Python. Recently, I get stuck with the problem of
sorting by two criteria. In brief, I have a two-dimensional list (for
a table or a matrix). Now, I need to sort by two columns, but I cannot
figure out how to do that. I read somewhere that it is possible to do:
>>>table.sort().sort()
but it does not work.
Can anyone help me with this?
PS: I am using Python under Ubuntu 6.06.
You can specify an arbitrary comparison function with the cmp key to
sort. IOW, use table.sort(cmp=f), where f is defined to compare table
entries (rows?) by whichever criteria are required.
Feb 10 '08 #2
On Sat, 09 Feb 2008 18:05:14 -0800, neocortex wrote:
Hello!
I am a newbie in Python. Recently, I get stuck with the problem of
sorting by two criteria. In brief, I have a two-dimensional list (for a
table or a matrix). Now, I need to sort by two columns, but I cannot
figure out how to do that.

Can you give a (small, simple) example of your data, and what you expect
if you sort it successfully?

I read somewhere that it is possible to do:
>table.sort().sort()
but it does not work.
No it doesn't, because the sort() method returns None, and None doesn't
have a sort() method of its own.

table.sort() will sort table in place, so you need something like this:
>>table.sort()
table.sort()
except naturally that just does the exact same sort twice in a row, which
is silly. So what you actually need is something like this:
>>table.sort(magic goes here)
table.sort(different magic goes here)
where the first piece of magic tells Python to sort by the first column,
and the second by the second column. But to do that, we need to know more
about how you're setting up the table.

I'm *guessing* that you probably have something like this:
table = [ ['fred', 35, 8], # name, age, score
['bill', 29, 8],
['betty', 30, 9],
['morris', 17, 4],
['catherine', 23, 6],
['anna', 45, 8],
['george', 19, 5],
['tanya', 27, 7],
]
Now let's sort it:

>>from operator import itemgetter
import pprint
table.sort(key=itemgetter(0)) # sort by name
table.sort(key=itemgetter(2)) # sort by score
pprint.pprint(table)
[['morris', 17, 4],
['george', 19, 5],
['catherine', 23, 6],
['tanya', 27, 7],
['anna', 45, 8],
['bill', 29, 8],
['fred', 35, 8],
['betty', 30, 9]]

Does this help?

--
Steven
Feb 10 '08 #3
Hello!
Thank you all, so much! Now I can do double-criteria sort in at least
three ways. More than I have expected.

Best,
PM
Feb 10 '08 #4
[repost]

Duncan Booth:
>from operator import itemgetter
lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
lst.sort(key=itemgetter(1))
lst.sort(key=itemgetter(2))
lst
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]
A little known thing from Python 2.5:
>>from operator import itemgetter
lst = [(1,2,4),(3,2,1),(2,2,2),(2,1,4),(2,4,1)]
sorted(lst, key=itemgetter(2, 1))
[(3, 2, 1), (2, 4, 1), (2, 2, 2), (2, 1, 4), (1, 2, 4)]

Bye,
bearophile
Feb 11 '08 #5
On Feb 11, 10:47 am, bearophileH...@lycos.com wrote:
[...]
A little known thing from Python 2.5:
[...]
>sorted(lst, key=itemgetter(2, 1))
Cute, thanks :-)

--bjorn
Feb 11 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
by: googleboy | last post by:
I didn't think this would be as difficult as it now seems to me. I am reading in a csv file that documents a bunch of different info on about 200 books, such as title, author, publisher, isbn,...
3
by: Math Preregistration System | last post by:
I'm using a std::list as a container for some pointers to objects, for example list< C* > lst; I would like to sort them using two different criteria, say first by C.first and then by...
4
by: Nhmiller | last post by:
This is directly from Access' Help: "About designing a query When you open a query in Design view, or open a form, report, or datasheet and show the Advanced Filter/Sort window (Advanced...
0
by: joseph speigle | last post by:
hi, To see the query results in native language see http://database.sarang.net/?inc=read&aid=5368&criteria=pgsql&subcrit=qna&id=&limit=20&keyword=&page=1 the simpler url is ...
2
by: missnaughton | last post by:
Hi I'm designing a query for our hockey coach to print out players' names to stick on game sheets. I could sort the query results based on Jersey number, but the problem is the 2 goalie names...
3
by: Peter Olcott | last post by:
How does not specify the sort criteria for Generic.List ?? The way that this is done in C++ STL is to implement operator<(), how is this done in C# and DotNet for Generic.List ???
0
by: JosAH | last post by:
Greetings, I was asked to write a Tip Of the Week; so here goes: a lot of topics are started here in this forum (and a lot of other forums too) mentioning a problem about sorting data. ...
1
by: Socko | last post by:
I'm trying to fix an sub routine in an VB module that basically reads in a MS database and writes it to an Excel Spread sheet. It works just fine except that the data isn't sorted correctly. I have...
3
by: fastestindian | last post by:
Hi, I am working on the project where i show a list of Log Records. my list is as follows. Original list Id Time Event Details 1 1 Error1 xyz 2 1 ...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.