[portland] Sorting A List of Tuples
jason kirtland
jek at discorporate.us
Thu Nov 8 18:48:09 CET 2007
Rich Shepard wrote:
> All the information I find on sorting lists assumes the list has only a
> single value to be sorted. What to do with multiple values when the sort is
> on the second or third item and all must be kept together?
>
> I have lists of tuples which I'd like to sort on the second item while
> retaining the relationships among the item pairs.
>
> Could I do
> terms.sort([][1])
> ?
The array 'sort' method and the 'sorted' function both take an optional
'key' function. The function is applied to each item in the list and
the result is used for comparison instead of the list value itself.
If you only want to consider the second item in the tuple, the operator
module's 'itemgetter' is perfect:
>>> stuff = [(1,2),(3,3),(2,1),(1,3)]
>>> from operator import itemgetter
>>> sorted(stuff, key=itemgetter(1))
[(2, 1), (1, 2), (3, 3), (1, 3)]
You can also get fancy and do some tuple-reordering for a stable sort:
>>> last_then_first = lambda t: (t[1], t[0])
>>> last_then_first( (1, 0) )
(0, 1)
>>> sorted(stuff, key=last_then_first)
[(2, 1), (1, 2), (1, 3), (3, 3)]
-j
More information about the Portland
mailing list