While we're talking about annoyances
Steven D'Aprano
steve at REMOVEME.cybersource.com.au
Wed May 2 02:19:56 EDT 2007
On Wed, 02 May 2007 06:10:54 +0000, Tim Roberts wrote:
> Michael Hoffman <cam.ac.uk at mh391.invalid> wrote:
>>
>>Hint: if you find yourself using a decorate-sort-undecorate pattern,
>>sorted(key=func) or sequence.sort(key=func) might be a better idea.
>
> Is it? I thought I remember reading on this very list some years ago that
> the performance of sequence.sort became much, much worse when a key
> function was supplied.
You're probably thinking of a comparison function:
sequence.sort(cmp=lambda x, y: cmp(y, x))
is a slow way of sorting a sequence in reverse order. The fast
way is the two liner:
sequence.sort()
sequence.reverse()
Faster(?) still is:
sequence.sort(reverse=True)
> I've tended to favor the "Schwarzian transform" (decorate-sort-undecorate)
> because of that.
That's what the key= argument does. cmp= is slow because the comparison
function is called for EVERY comparison. The key= function is only called
once per element.
--
Steven D'Aprano
More information about the Python-list
mailing list