Need Help sorting alphabetically.

Duncan Booth duncan at rcp.co.uk
Wed Dec 20 09:45:30 EST 2000


chris at araidesign.com (Chris Arai) wrote in
<3A3F1A91.A7ED9182 at araidesign.com>: 

>Hi,
>
>This seems like it should be obvious, but it is evading me!
>
>I would like to sort alphabetically (I'm not sure that is the correct
>term) so that strings of alpha numerics sort alphabetically instead of
>by ASCII order.
>
>eg:
>>>> m=['Pg95_100.GIF',
>'Pg9_100.GIF','Pg95A_100.gif','Pg9A_100.gif','Pg10_100.gif']
>>>> m.sort()
>>>> m
>['Pg10_100.gif', 'Pg95A_100.gif', 'Pg95_100.GIF', 'Pg9A_100.gif',
>'Pg9_100.GIF']
>
>
>I would like the order to be
>['Pg9_100.GIF', 'Pg9A_100.gif', 'Pg10_100.gif, 'Pg95_100.GIF',
>Pg95A_100.gif' ]
>
>What is the obvious answer??
>
Try this:
---- begin cut ---
import re
from string import lower

def make_key(value, pattern = re.compile('(\d+)|(\D+)')):
    vals = pattern.split(value)
    res = []
    for i in range(1, len(vals), 3):
        if vals[i]:
            res.append(int(vals[i]))
        else:
            res.append(lower(vals[i+1]))
    return res

def cleversort(list):
    l1, res = [], []
    for v in list: l1.append((make_key(v), v))
    l1.sort()
    for k, v in l1: res.append(v)
    return res

m=['Pg95_100.GIF',
'Pg9_100.GIF','Pg95A_100.gif','Pg9A_100.gif','Pg10_100.gif'] 

print cleversort(m)

----- end cut ----
The output is:
['Pg9_100.GIF', 'Pg9A_100.gif', 'Pg10_100.gif', 'Pg95_100.GIF',
'Pg95A_100.gif'] as you requested.

This sorts each sequence of digits as its numeric value, and each
sequence of non digits as its lowercase equivalent (which I think is what
you were asking for). 



More information about the Python-list mailing list