[Tutor] Newbie: Sorting lists of lists

Forrest Y. Yu forrest.yu at gmail.com
Thu Jun 19 04:48:50 CEST 2008


>
> Message: 8
> Date: Wed, 18 Jun 2008 19:30:05 -0500
> From: Keith Troell <ktroell at mac.com>
> Subject: [Tutor] Newbie: Sorting lists of lists
> To: tutor at python.org
> Message-ID: <2AAF54E8-95D9-4CB3-BD1E-CA2270E4B165 at mac.com>
> Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed
>
> 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?


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

Yuan (yet unlovely another newbie)


>
> Keith
>
> A++ G++ PKR+ !PEG- B++ TB ADB- M+++ CHOW++
> http://zbigniew.pyrzqxgl.com/bargegeek.html
>
>
>
>
> ------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
> End of Tutor Digest, Vol 52, Issue 51
> *************************************
>



-- 
Fran Lebowitz  - "You're only has good as your last haircut."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20080619/8447ea1c/attachment.htm>


More information about the Tutor mailing list