[portland] Sorting A List of Tuples

Matt McCredie mccredie at gmail.com
Thu Nov 8 18:56:16 CET 2007


On Nov 8, 2007 9:25 AM, Rich Shepard <rshepard at appl-ecosys.com> 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])
> ?
>
>    A pointer to a reference would be fine.
>
> Rich

First the example:

>>> import operator
>>> terms
[(0, 9), (1, 8), (2, 7), (3, 6), (4, 5), (5, 4), (6, 3), (7, 2), (8, 1), (9, 0)]
>>> terms.sort(key=operator.itemgetter(1))
>>> terms
[(9, 0), (8, 1), (7, 2), (6, 3), (5, 4), (4, 5), (3, 6), (2, 7), (1, 8), (0, 9)]

Then the explanation:

operator.itemgetter(n) returns a callable object (function) that when
passed a sequence will always return the nth item of the sequence.

so...

>>> foo = operator.itemgetter(3)
>>> foo([0,1,2,3])
3
>>> foo('abcd')
'd'

The key parameter to sort accepts a callable object (function) that
will be called on each item in the list to determine the actual value
to sort by. So, the example I gave you is essentially just saying,
sort by the item at index 1 of each tuple in the list terms.

Hope this helps,

Matt


More information about the Portland mailing list