Python使用特殊的比较器查找最小对象 [英] Python Find minimum object using special comparator
本文介绍了Python使用特殊的比较器查找最小对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我得到了我的问题回答了有关如何找到最小值的问题,但是如果我想要最小的对象怎么办?我们是否可以类似地简化此代码?
So I got my question answered on how to find the minimum value, but what if I want the minimum object? Can we similarly simplify this code?
min = 9999
minChild = None
for child in currentRoot.children:
if child.score < min:
min = child.score
minChild = child
recurseWriteBook(child, depth+1)
推荐答案
使用内置函数 min(iterable [,key]):
>>> class Foo(object):
... def __init__(self, value):
... self.value = value
...
>>>
>>> l = [Foo(2), Foo(1), Foo(3)]
>>>
>>>
>>> min_foo = min(l, key = lambda x: x.value)
>>>
>>> min_foo.value
1
您告诉它哪个密钥
/用于比较对象的属性。
You tell it which key
/attribute to use to compare objects.
这篇关于Python使用特殊的比较器查找最小对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文