On Wed, Jun 18, 2008 at 10:48 PM, Forrest Y. Yu <[EMAIL PROTECTED]> wrote: > I know, it's NOT beautiful code, but it seems work. If you have no better > way, try this: > > """Sort on the second elements.""" > def xchg12(l) : > for m in l: > m[0], m[1] = m[1], m[0] > > l = [[1, 2, 3], [2, 3, 1], [3, 2,1], [1, 3, 2]] > print l > xchg12(l) > l.sort() > xchg12(l) > print l
This is not too far from the decorate-sort-undecorate idiom which used to be the standard way to do something like this. Instead of modifying the elements of the original list, create a new list whose elements are the key and the item from the old list, and sort that: In [6]: l = [[1, 2, 3], [2, 3, 1], [3, 2, 1], [1, 3, 2]] In [7]: m = [ (i[1], i) for i in l ] In [8]: m.sort() In [9]: m Out[9]: [(2, [1, 2, 3]), (2, [3, 2, 1]), (3, [1, 3, 2]), (3, [2, 3, 1])] In [10]: l = [ i[1] for i in m ] In [11]: l Out[11]: [[1, 2, 3], [3, 2, 1], [1, 3, 2], [2, 3, 1]] Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor