Jonathan Prior
Jonathan Prior

Reputation: 6294

Sorting a tuple that contains lists

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?

Upvotes: 0

Views: 3511

Answers (4)

Joe Beda
Joe Beda

Reputation: 2761

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])

Upvotes: 7

mluebke
mluebke

Reputation: 8819

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.

Upvotes: 5

SingleNegationElimination
SingleNegationElimination

Reputation: 156308

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])

Upvotes: 1

Ben Blank
Ben Blank

Reputation: 56634

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.

Upvotes: 1

Related Questions