No numerical sort in python ?

1. May 10, 2005

nameta9

No numerical sort in python ?!?!?

I was really surprised to see that python can't do such an elementary operation!

I am trying to do a numerical sort in python on an array. I am using python for windows (DOS). In perl you can simply write sort{$a<=>$b}@a and this will sort it according to the value of the numerical string, (not the alphabetical value). I am looking for something similar in python but could only find a reference to sourceforge numpy where I have to download a large piece of source code in C and recompile it locally. Is there a simpler solution ? thanks.....

Last edited: May 10, 2005
2. May 10, 2005

master_coda

x.sort(lambda a,b: cmp(int(a), int(b)))

where x is the list you want to sort. Of course, you could just say x.sort() if you just stored your list of numbers as an actual list of numbers and not a list of strings.

3. May 10, 2005

nameta9

Thanks master. Getting close but it doesn't seem to work. My list is of the format x[1]="1123 wwww", x[2]="345 asdd", etc. What should I put in int(a) and int(b) ? when this is sorted "1123 wwwww" is before "345 asdd" because it is doing an alphabetical sort and not a numerical sort. Thanks for any suggestions.

4. May 10, 2005

master_coda

Try int(a.split()[0]) and int(b.split()[0]).

5. May 11, 2005

nameta9

It doesn't even do this! I also tried with a.append(22) etc. I don't think python sorts numerically in any case! Maybe it is because python on windows is too immature ?

a=[]
a.append(int('22'))
a.append(int('111'))
a.append(int('9'))
a.append(int('12'))

a.sort()

for mat in a:print mat

Second EDIT::::

OK it has to be done like this:

def descendingCmp(a,b):
return cmp(a,b)

a=[]
a.append(22)
a.append(111)
a.append(9)
a.append(12)

a.sort(descendingCmp)

for mat in a:print mat

It is simpler in perl, maybe they should simply create a built in function for sort numeric.......

Last edited: May 11, 2005
6. May 11, 2005

faust9

So, you are decrying python because you did not take the time to even quickly read through the python docs? You don't need to declare variable types in python. 4 is a number and '4' is a string.

Here, try this:
Code (Text):

a=[123,234,542,821,111,54,767,23453,90,9,0,1,321]
a
a.sort()
a

it will work on windows, mac, linux, unix...

If you really want to get crazy do this:
Code (Text):

a=[(123,'jack'),(1,'work'),(234,'a'),(542,'boy'),(111,'makes'),(90,'play'),(9,'and'),(0,'all'),(321,'dull'),(54,'no')]
a
a.sort()
a

it's easy.

Here is a good source for python knowledge:
http://www.python.org/doc/2.4.1/tut/tut.html [Broken]

as is this:
http://diveintopython.org/

You should thumb through the docs and brush up a little. Python is day and night easier than perl.

Last edited by a moderator: May 2, 2017
7. May 11, 2005

master_coda

This code works fine for me. When I run it I get:

9
12
22
111