Combined natural and unnatural list sorting
agriff at tin.it
Wed Jun 16 08:39:19 CEST 2004
On Wed, 16 Jun 2004 00:23:47 GMT, Derek Basch <dbasch at yahoo.com>
>> > I need to sort a list using an unnatural sequence.
This is my first attempt, I'm new to python so may be there are
better ways to do it...
>>> def scol(x,y):
... (cx,sx) = x.split("/")
... (cy,sy) = y.split("/")
... if sx==sy: return cmp(cx,cy)
... return cmp(xs[sx],xs[sy])
>>> xs = dict(S=1,M=2,L=3)
>>> a = ["White/M","White/L","White/S",
['White/S', 'Blue/M', 'White/M', 'Orange/L', 'Purple/L', 'White/L']
I can think to a probably faster way if the list is big...
just "transform" every string to a (xs[sx],cx) tuple once;
then do a regular sort, then transform back to the string form.
More information about the Python-list