compare function in sort function of lists 
Author Message
 compare function in sort function of lists

Hi all:
        I'm trying to sort a list numerically, e.g.,  so that 11 comes
AFTER 2. The documentation says I need to pass sort() a compare
function...but I can't find an example of this.

This should be an easy one for you folks :)

TIA,

Gabe Newcomb
Software Test Automation Engineer
425.372.2732
Noetix Corporation
www.noetix.com



Wed, 22 Sep 2004 06:21:14 GMT  
 compare function in sort function of lists


Quote:
> Hi all:
>       I'm trying to sort a list numerically, e.g.,  so that 11 comes
> AFTER 2. The documentation says I need to pass sort() a compare
> function...but I can't find an example of this.

> This should be an easy one for you folks :)

>>> l = [1,5,11,2,67,23]
>>> l.sort()
>>> l

[1, 2, 5, 11, 23, 67]
Quote:
>>> def comp(a,b): # sort in reverse

...   if b < a: return -1
...   elif b == a: return 0
...   else: return 1
...
Quote:
>>> l.sort(comp)
>>> l

[67, 23, 11, 5, 2, 1]




Wed, 22 Sep 2004 06:35:58 GMT  
 compare function in sort function of lists
[Gabe Newcomb]

Quote:
>    I'm trying to sort a list numerically, e.g.,  so that 11 comes
> AFTER 2.

I suspect you're sorting a list of strings, not numbers (in python before
2.3, these will display 0 and 1 respectively):

Quote:
>>> '11' > '2'
False
>>> 11 > 2
True

> The documentation says I need to pass sort() a compare
> function...but I can't find an example of this.

You don't *need* to pass a compare function, and usually shouldn't.

Quote:
>>> x = ['2', '11']
>>> x.sort()
>>> x
['11', '2']
>>> y = map(int, x)  # convert the strings to integers
>>> y
[11, 2]
>>> y.sort()
>>> y
[2, 11]



Wed, 22 Sep 2004 06:59:07 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. Function to merge sorted lists

2. function while true - list function?

3. TIP #15: Functions to List and Detail Math Functions

4. VC++ calling fortran function and fortran function calling a c++ function

5. Calling functions from functions from functions ...

6. Puzzler: Comparing Functions

7. Comparing Arrays Function Needed

8. Compare object-oriented and function-oriented ....

9. Compare VI function

10. Mem compare function

11. Instantiating A Generic Compare Function

12. Comparing date functions with database date records.

 

 
Powered by phpBB® Forum Software