Python min function with a list of objects

2020-05-29 21:12发布

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)]

标签: python
4条回答
我欲成王,谁敢阻挡
2楼-- · 2020-05-29 21:47

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)>
查看更多
再贱就再见
3楼-- · 2020-05-29 21:52

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
查看更多
够拽才男人
4楼-- · 2020-05-29 21:57

It's:

min(li, key=lambda x: x.number)

you need a function that accepts a SpecialNumber and returns its element.

查看更多
做个烂人
5楼-- · 2020-05-29 22:10

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
查看更多
登录 后发表回答