views:

204

answers:

4

I have a similar question to this one but instead my tuple contains lists, as follows:

mytuple = (
 ["tomato", 3],
 ["say", 2],
 ["say", 5],
 ["I", 4],
 ["you", 1],
 ["tomato", 6],
)

What's the most efficient way of sorting this?

+1  A: 

You will have to instantiate a new tuple, unfortunately: something like

mytuple = sorted(mytuple)

should do the trick. sorted won't return a tuple, though. wrap the call in tuple() if you need that. This could potentially be costly if the data set is long.

If you need to set on the second element in the sublists, you can use the key parameter to the sorted function. You'll need a helper function for that:

mytuple = sorted(mytuple, key=lambda row: row[1])
TokenMacGuy
+1  A: 

The technique used in the accepted answer to that question (sorted(..., key=itemgetter(...))) should work with any iterable of this kind. Based on the data you present here, I think the exact solution presented there is what you want.

Ben Blank
+6  A: 

You can get a sorted tuple easy enough:

>>> sorted(mytuple)
[['I', 4], ['say', 2], ['say', 5], ['tomato', 3], ['tomato', 6], ['you', 1]]

This will sort based on the items in the list. If the first two match, it compares the second, etc.

If you have a different criteria, you can provide a comparison function.

Updated: As a commenter noted, this returns a list. You can get another tuple like so:

>>> tuple(sorted(mytuple))
(['I', 4], ['say', 2], ['say', 5], ['tomato', 3], ['tomato', 6], ['you', 1])
Joe Beda
By "get a sorted tuple" do you mean "create a new tuple that's sorted"?
S.Lott
The sorted() function works just fine.
Jonathan Prior
This is hugely inefficient however - why not just take mluebke's advice and use a list to begin with? S. Lott is right -- you cannot sort a tuple in place.
Justin Standard
I'm trying to process output from psycopg2, which uses Python's DB-API and therefore outputs tuples.
Jonathan Prior
The DB-API .fetch functions typically return lists (rows) of tuples (records), not tuples of lists. Please provide sample code and data.
ΤΖΩΤΖΙΟΥ
+4  A: 

You cannot sort a tuple.

What you can do is use sorted() which will not sort the tuple, but will create a sorted list from your tuple. If you really need a sorted tuple, you can then cast the return from sorted as a tuple:

mytuple = tuple(sorted(mytuple, key=lambda row: row[1]))

This can be a waste of memory since you are creating a list and then discarding it (and also discarding the original tuple). Chances are you don't need a tuple. Much more efficient would be to start with a list and sort that.

mluebke