[Tutor] Newbie: Sorting lists of lists
John Fouhy
john at fouhy.net
Thu Jun 19 02:50:47 CEST 2008
On 19/06/2008, Keith Troell <ktroell at mac.com> wrote:
> Let's say I have a list of lists l == [[1, 2, 3], [2, 3, 1], [3, 2, 1], [1,
> 3, 2]]
>
> If I do a l.sort(), it sorts on the first element of each listed list:
>
> >>> l.sort()
> >>> l
> [[1, 2, 3], [1, 3, 2], [2, 3, 1], [3, 2, 1]]
>
>
> How can I sort on the second or third elements of the listed lists?
Use the key= option in sort, together with the operator module:
>>> l = [[1,2,3], [2,3,1], [3,2,1], [1,3,2]]
>>> import operator
>>> l.sort(key=operator.itemgetter(1))
>>> l
[[1, 2, 3], [3, 2, 1], [2, 3, 1], [1, 3, 2]]
>>> l.sort(key=operator.itemgetter(2))
>>> l
[[3, 2, 1], [2, 3, 1], [1, 3, 2], [1, 2, 3]]
>>>
operator.itemgetter(i) is basically equivalent to a function defined as follows:
def f(lst):
return lst[i]
If you have an old version of python, this may not work. As an
alternative, try googling for "decorate-sort-undecorate".
--
John.
More information about the Tutor
mailing list