Combined natural and unnatural list sorting

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Tue Jun 15 23:51:42 CEST 2004


Derek Basch wrote:

> Hello All,
> 
> I need to sort a list using an unnatural sequence.
> 
> I have a list like so:
> 
> foo = ["White/M", "White/L", "White/XL", "White/S", "Black/S",
> "Black/M"] 
> 
> print foo.sort()
> 
> ['White/L', 'White/M', 'White/S', 'White/XL', 'Black/M', 'Black/S']
> 
> 
> The order that I actually need is:
> 
> ["White/S","White/M", "White/L", "White/XL", "Black/S", "Black/M"]
> 
> 
> So, in other words, I need the colors sorted alphabetically and the
> the sizes sorted logically.
> 
> I looked for a while at using comparison functions with sort but I
> don't think that will work. Anyone been down this road? Suggestions?

Of course a comparison function will work - you just have to write it
correctly.

I'll using DSU (decorate-sort-undecorate) for this example. Every
comparison function can be converted to DSU and vice versa.

In the comparison function, you should do the following:

1. Split the string into two parts (i.e. split on '/').

2. Do a string compare on the first part (colour).

3. If the first part compares equal, look up an equivalent value for
each size and compare those. I would suggest building a dictionary
mapping the (string) size to an integer e.g.

SIZE_MAP = {
    'S': 1,
    'M': 2,
    'L': 3,
    'XL': 4,
}

Tim Delaney




More information about the Python-list mailing list