问题
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)
回答1:
Use built-in function 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.
回答2:
You know your types (list/tuples) and how to adjust them, so you can use technique like this:
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)
回答3:
I used the answer I selected plus the answer from my other question to use this:
minChild = min(currentRoot.children, key = lambda child: child.score)
来源:https://stackoverflow.com/questions/37980286/python-find-minimum-object-using-special-comparator