How can use the key
argument for the min
function to compare a list of objects's 1 attribute?
Example
class SpecialNumber:
def __init__(self, i):
self.number = i
li = [SpecialNumber(1), SpecialNumber(3), SpecialNumber(2)]
How can use the key
argument for the min
function to compare a list of objects's 1 attribute?
Example
class SpecialNumber:
def __init__(self, i):
self.number = i
li = [SpecialNumber(1), SpecialNumber(3), SpecialNumber(2)]
I'd do it by overriding
__cmp__
the getattr version is faster
It's:
you need a function that accepts a
SpecialNumber
and returns its element.http://docs.python.org/library/operator.html#operator.attrgetter
Sample interactive session: