"Kent Johnson" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
On Wed, Jun 18, 2008 at 8:30 PM, Keith Troell <[EMAIL PROTECTED]> 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= parameter of sort to specify the sort key.
operator.itemgetter is convenient for the actual key:
In [3]: from operator import itemgetter
In [4]: l.sort(key=itemgetter(1))
In [5]: l
Out[5]: [[1, 2, 3], [3, 2, 1], [2, 3, 1], [1, 3, 2]]
A longer explanation is here:
http://personalpages.tds.net/~kent37/kk/00007.html
Kent
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
You can use a lambda that builds the key you want to sort on from the
original element:
L=[[1,2,3],[2,3,1],[3,2,1],[1,3,2]]
Sort on 2nd value:
sorted(L,key=lambda x: x[1])
[[1, 2, 3], [3, 2, 1], [2, 3, 1], [1, 3, 2]]
Sort on 2nd, then by 3rd value
sorted(L,key=lambda x: (x[1],x[2]))
[[3, 2, 1], [1, 2, 3], [2, 3, 1], [1, 3, 2]]
-Mark
_______________________________________________
Tutor maillist - Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor