Python - 实例变量列表的最小值
我是 Python 新手,我真的很喜欢 min
函数。
>>>min([1,3,15])
0
但是,如果我有一个实例列表,并且它们都有一个名为 number
的变量,该怎么办?
class Instance():
def __init__(self, number):
self.number = number
i1 = Instance(1)
i2 = Instance(3)
i3 = Instance(15)
iList = [i1,i2,i3]
我真的需要像
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 beautiful pythonic way 那样吗?
I'm new to Python and I really love the min
function.
>>>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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
OOP 方法是实现
__lt__
:另一种方法是
imin = min(iList, key=lambda x:x.number)
像
sort、min、 max
全部采用key
参数。您给出一个函数,该函数接受一个项目并在比较时返回代表该项目的任何内容。The OOP way would be to implement
__lt__
:Another way is
imin = min(iList, key=lambda x:x.number)
Functions like
sort, min, max
all take akey
argument. You give a function that takes an item and returns whatever should stand for this item when comparing it.相同的
key
参数也适用于sort
,用于以 Python 方式实现decorate-sort-undecorate 习惯用法。The same
key
argument also works withsort
, for implementing the decorate-sort-undecorate idiom Pythonically.生成器语法:
key
功能:Generator syntax:
key
function: