[Tutor] Sorting a list

vince spicer vinces1979 at gmail.com
Wed May 13 18:44:11 CEST 2009


you can pass sort a custom compare function


Simple ex:

def compare(x,y):
    try:
        return cmp(int(x), int(y))
    except:
        pass
    try:
        int(x)
    except:
        return -1
    try:
        int(y)
    except:
        return 1
    return 0


x = [4, 6, 'word', 3, 9]
x.sort(cmp=compare)

>> ['word', 3,4, 6, 9]


On Wed, May 13, 2009 at 10:25 AM, Timo <timomlists at gmail.com> wrote:

> Hello,
>
> I don't think this should be difficult, so maybe I look over it. But I
> can't seem to find the solution.
>
> I have a list with one word and a couple of numbers. Now I want the word to
> be kept in the first location and the numbers to be sorted.
>
> So this:
> [4, 6, 'word', 3, 9]
>
> should be:
>
> ['word', 3, 4, 6, 9]
>
> Timo
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090513/920b2595/attachment.htm>


More information about the Tutor mailing list