[Tutor] Re: list sorting problem (help!)

Emile van Sebille emile@fenx.com
Sun, 8 Sep 2002 07:58:10 -0700


Thomi:
> ok, i have a problem. i have a list, like this:
>
> ['email me','My programs','Web Design','Web Hosting']
>
> and i want to sort them, so i can say something like "the link 'My
> programs' should ALWAYS appear at the top". i thought I'd use a
> weighting system, so the 'My programs' list item would be weighted 0,
> and so always appear at the top. the next one would be '1', then '2',
> etc. etc. etc. i could give 'contact me' a weighting of 999, so it
would
> always appear at the bottom.
>

thisset = ['email me','My programs','Web Design','Web Hosting']

sortwghts = {'email me':999,'My programs':0,'Web Design':40,'Web
Hosting':200}
thisset.sort(lambda this, other: cmp (sortwghts[this],
sortwghts[other]))

print thisset
##  -> ['My programs', 'Web Design', 'Web Hosting', 'email me']

sortwghts = {'email me':999,'My programs':2000,'Web Design':2040,'Web
Hosting':2200}
thisset.sort(lambda this, other: cmp (sortwghts[this],
sortwghts[other]))

print thisset
## -> ['email me', 'My programs', 'Web Design', 'Web Hosting']


Note:  Depending on your python version, the lambda may need to start:
lambda this, other, sortwghts=sortwghts: cmp


HTH,

--

Emile van Sebille
emile@fenx.com

---------