Python Find minimum object using special comparator

坚强是说给别人听的谎言 提交于 2019-12-11 05:55:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!