如何使用key
函数的min
参数来比较对象的1个属性列表?
实施例
class SpecialNumber:
def __init__(self, i):
self.number = i
li = [SpecialNumber(1), SpecialNumber(3), SpecialNumber(2)]
答案 0 :(得分:38)
http://docs.python.org/library/operator.html#operator.attrgetter
from operator import attrgetter
min_num = min(li,key=attrgetter('number'))
示例交互式会话:
>>> 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
答案 1 :(得分:32)
这是:
min(li, key=lambda x: x.number)
你需要一个接受SpecialNumber
并返回其元素的函数。
答案 2 :(得分:13)
我会通过覆盖__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)>
答案 3 :(得分:1)
getattr版本更快
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