sorting ascending/descending with operator.attrgetter

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Apr 1 00:57:10 CEST 2010


On Wed, 31 Mar 2010 12:05:24 -0700, Patrick Maupin wrote:

> You can provide a cmp function to the string sort method, e.g. cmp =
> lambda x,y: -cmp(x.a, y.a) or cmp(x.b, y.b)

String sort method?

>>> ''.sort
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'sort'
>>> import string
>>> string.sort
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'sort'

Did you mean list sort method?



> You can also possibly gain some efficiency by using key instead of cmp.

That is an impressive understatement. key is called once for every item, 
cmp is called once for every comparison. cmp has been dropped from Python 
3.x because its performance is poor.



-- 
Steven



More information about the Python-list mailing list