Python min function with a list of objects

后端 未结 4 1154
攒了一身酷
攒了一身酷 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: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
    

提交回复
热议问题