sorting a list of list

Tim Chase python.list at tim.thechases.com
Tue Nov 20 20:56:00 EST 2007


> are there available library or pythonic algorithm for sorting a list
> of list depending on the index of the list inside the list of my
> choice?

The built-in sorted() function and the sort() method on various
collections take an optional "key=function" keyword paramater
with which you can pass a function (lambdas are convenient) to
extract the bit on which you want to compare:

>>> d_list = [
...     ['a', 1, 9],
...     ['b', 2, 8],
...     ['c', 3, 7],
...     ['d', 4, 6],
...     ['e', 5, 5],
... ]
>>> print sorted.__doc__
sorted(iterable, cmp=None, key=None, reverse=False) --> new
sorted list
>>> sorted(d_list, key=lambda x: x[2]) # sort by the 3rd item
[['e', 5, 5], ['d', 4, 6], ['c', 3, 7], ['b', 2, 8], ['a', 1, 9]]
>>> sorted(d_list, key=lambda x: x[1]) # sort by the 2nd item
[['a', 1, 9], ['b', 2, 8], ['c', 3, 7], ['d', 4, 6], ['e', 5, 5]]
>>> sorted(d_list, key=lambda x: x[0]) # sort by the 1st item
[['a', 1, 9], ['b', 2, 8], ['c', 3, 7], ['d', 4, 6], ['e', 5, 5]]

-tkc






More information about the Python-list mailing list