How to Sort this array

Sean 'Shaleh' Perry shalehperry at
Sat Oct 26 10:28:25 CEST 2002

On Friday 25 October 2002 23:23, Hai Wu wrote:
> How to sort an array with numbers like 021025_11441 in it? It needs to be
> sorted first by the number before '_', then sorted by the number after '_'?
> How to do it using a customized sort function?

the usual tactic is to write a comparison function and pass this to .sort().

parts = ['021025_11441', '876432_19532', '243756_98652', '565438_67453']

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


The part_sort function uses the builtin cmp() which returns -1 if a is less 
than b, 0 if a equals b, or 1 is a is greater than b.  So far we are no 
better than just calling .sort() without a function.  Let's make a better 

def part_sort2(a, b):
    a_left, a_right = a.split('_')
    b_left, b_right = b.split('_')

    return cmp(int(a_left), int(b_left)) or cmp(int(a_right), int(b_right))

this splits the values on underscore and then calls cmp().  We use int() to 
turn each piece into a number for better sorting.  The sorter works like 

if a_left < b_left:
    return -1
else if a_left > b_left:
    return 1
else if a_right < b_right:
    return -1
else if a_right > b_right:
    return 1
    return 0

the key is the second call to cmp() is not made if the first one yields a 
result other than equal to.

Hope this helps.

More information about the Python-list mailing list