开发者

Python - Minimum of a List of Instance Variables

开发者 https://www.devze.com 2023-01-14 06:15 出处:网络
I\'m new to Python and I really love the min fun开发者_高级运维ction. >>>min([1,3,15])

I'm new to Python and I really love the min fun开发者_高级运维ction.

>>>min([1,3,15])
0

But what if I have a list of instances, and they all have a variable named number?

class Instance():
    def __init__(self, number):
        self.number = number

i1 = Instance(1)
i2 = Instance(3)
i3 = Instance(15)
iList = [i1,i2,i3]

Do I really have to something like

lowestI = iList[0].number
for i in iList:
    if lowestI > iList[i].number: lowestI = iList[i].number
print lowestI

Can't I use min in a nice pythonic way?


The OOP way would be to implement __lt__:

class Instance():
    def __init__(self, number):
        self.number = number

    def __lt__(self, other):
        return self.number < other.number
        # now min(iList) just works

Another way is

imin = min(iList, key=lambda x:x.number)

Functions like sort, min, max all take a key argument. You give a function that takes an item and returns whatever should stand for this item when comparing it.


from operator import attrgetter
min( iList, key = attrgetter( "number" ) )

The same key argument also works with sort, for implementing the decorate-sort-undecorate idiom Pythonically.


Generator syntax:

min(i.number for i in iList)

key function:

min(iList, key=lambda i: i.number)


min(iList, key=lambda inst: inst.number)
0

精彩评论

暂无评论...
验证码 换一张
取 消