Python min function with a list of objects

后端 未结 4 1126
攒了一身酷
攒了一身酷 2020-12-15 17:08

How can use the key argument for the min function to compare a list of objects\'s 1 attribute?

Example

class SpecialNumber:         


        
相关标签:
4条回答
  • 2020-12-15 17:14

    It's:

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

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

    0 讨论(0)
  • 2020-12-15 17:29

    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
    
    0 讨论(0)
  • 2020-12-15 17:32

    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)>
    
    0 讨论(0)
  • 2020-12-15 17:34

    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
    
    0 讨论(0)
提交回复
热议问题