How can use the key
argument for the min
function to compare a list of objects\'s 1 attribute?
Example
class SpecialNumber:
It's:
min(li, key=lambda x: x.number)
you need a function that accepts a SpecialNumber
and returns its element.
the getattr version is faster
import random
from operator import attrgetter
class Test:
def __init__(self):
self.a = random.random()
t = [Test() for i in range(10000)]
%timeit min(t, key=lambda x: x.a)
1000 loops, best of 3: 790 µs per loop
%timeit min(t,key=attrgetter('a'))
1000 loops, best of 3: 582 µs per loop
I'd do it by overriding __cmp__
class SpecialNumber:
def __init__(self, i):
self.number = i
def __repr__(self):
return '<SpecialNumber(%d)>' % self.number
def __cmp__(self, other):
return cmp(self.number, other.number)
li = [SpecialNumber(1), SpecialNumber(3), SpecialNumber(2)]
print min(li) # <SpecialNumber(1)>
http://docs.python.org/library/operator.html#operator.attrgetter
from operator import attrgetter
min_num = min(li,key=attrgetter('number'))
Sample interactive session:
>>> li = [SpecialNumber(1), SpecialNumber(3), SpecialNumber(2)]
>>> [i.number for i in li]
[1, 3, 2]
>>> min_num = min(li,key=attrgetter('number'))
>>> print min_num.number
1