所以我得到my question answered关于如何找到最小值,但如果我想要最小对象怎么办?我们可以类似地简化这段代码吗?
min = 9999
minChild = None
for child in currentRoot.children:
if child.score < min:
min = child.score
minChild = child
recurseWriteBook(child, depth+1)
答案 0 :(得分: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
告诉它使用哪个key
/属性来比较对象。
答案 1 :(得分:0)
你知道你的类型(列表/元组)以及如何调整它们,所以你 可以使用这样的技术:
list_min = [1,2,3,4] # list to demonstrate
m = lambda mn,lst: filter(lambda x: x <mn,lst) # get the minimum out of list
minimum = 3 # test value
print m(minimum,list_min)
答案 2 :(得分:0)
我使用了我选择的答案加上我的其他问题的答案来使用它:
minChild = min(currentRoot.children, key = lambda child: child.score)