[Tutor] list sorting problem (help!)
Magnus Lycka
magnus@thinkware.se
Mon, 09 Sep 2002 01:18:01 +0200
At 23:41 2002-09-08 +1200, Thomi Richards wrote:
>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.
>
>could i ask some of you python experts to make me a simple procedure
>which would do this?? It's for a CGI, which has to load every page, so
>the emphasis should be on minimal size and speed.. thanks.
Sure thing,
thingsToSort = ['email me','My programs','Web Design','Web Hosting']
sortWeights = [(999,'email me'),
(0, 'My programs'),
(6, 'Web Design'),
(5, 'My rtyrty'),
(4, 'Web fghfgh'),
(3, 'My cvbcvb'),
(2, 'Web ertert'),
(1, 'Web Hosting'),
]
usedWithWeights = [x for x in sortWeights if x[1] in thingsToSort]
usedWithWeights.sort()
sortedThings = [x[1] for x in usedWithWeights]
print sortedThings
This is a variant of the Schwartzian transform (sp?). That's a Perl
thingie, but since .sort() is much slower with a sort function
supplied in Python, this is typically faster than to supply a function
to the sort() method.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se