Python使用特殊比较器查找最小对象
所以我开始学习如何找到最小值,但是如果我想要最小的对象呢?我们可以同样简化这个代码吗Python使用特殊比较器查找最小对象,python,comparator,Python,Comparator,所以我开始学习如何找到最小值,但是如果我想要最小的对象呢?我们可以同样简化这个代码吗 min = 9999 minChild = None for child in currentRoot.children: if child.score < min: min = child.score minChild = child
min = 9999
minChild = None
for child in currentRoot.children:
if child.score < min:
min = child.score
minChild = child
recurseWriteBook(child, depth+1)
min=9999
minChild=None
对于currentRoot.children中的子级:
如果child.score
您知道自己的类型(列表/元组)以及如何调整它们,所以
您可以使用以下技术:
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)
list_min=[1,2,3,4]#要演示的列表
m=lambda mn,lst:filter(lambda x:x使用内置函数:
您可以告诉它使用哪个键
/属性来比较对象。我使用了我选择的答案加上我其他问题的答案来使用这个:
minChild = min(currentRoot.children, key = lambda child: child.score)
您的递归是否已中断?您正在调用一个recurse…()
函数,不返回任何内容,不声明全局变量,也不从函数中获取返回值。您可以通过查看minChild.score并不保留min
(顺便说一句,建议您在链接问题中不要使用该名称)来删除几行内容,但不清楚您是否可以在不查看所有内容的情况下简化所有内容。但是,您不能在嵌套结构上简单地使用min()
。不,一切都正常,除了我必须将min=9999提高到1之外,还必须确保我仍然调用了我的函数以深入到树中。
minChild = min(currentRoot.children, key = lambda child: child.score)