How to Sort this array

Chermside, Michael mchermside at ingdirect.com
Mon Oct 28 10:27:52 EST 2002


> 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?

Others have already written in describing how to create your own cmp 
function to do customized sorting, and describing why you might NOT
want this approach if you particularly need speedy performance and
might prefer to pull out the numbers. I just want to point out one
other approach which MIGHT work for you.

Your sample number is given as "021025_11441". Now, that can't be
stored as an integer (since it's not a number, but rather two
numbers jointed by an underscore), so I'm presuming you have it
stored as a string. And in your example you show a leading zero.
Now if it's ALWAYS the case that both numbers in this string are
padded with leading zeros to make them a consistant length, then
you can get away with using STRING sorts.

    >>> biglist = [
    ... '021025_11441',
    ... '021025_11442',
    ... '021025_00398',
    ... '215983_00398',
    ... '000336_98043']
    >>> biglist.sort()
    >>> import pprint
    >>> pprint.pprint(biglist)
    ['000336_98043',
     '021025_00398',
     '021025_11441',
     '021025_11442',
     '215983_00398']

Of course, it won't work if there are ever entries like '336_398'
(entries with a different number of digits in either number).

-- Michael Chermside




More information about the Python-list mailing list