如何在计算其他类值的最小值后获取类方法的值



我有一个"Node"类,它接受参数x和y。类方法计算不同的值。我有多个此类实例,称为"节点"。我想要的是找到"fcost"最低的节点,并获取该节点的 x 和 y 坐标。

我不知道如何解决这个问题,所以如果你能帮助我,将不胜感激。

class Node():
    # Node class
    def __init__(self, y, x):
        self.y = y
        self.x = x        
    def gcost(self):
        return self.x + self.y
    def hcost(self):
        return self.x * self.y
    def fcost(self):
        return self.gcost() + self.hcost()  # method that indicates 
                                            # which node to choose 
node1 = Node(5,5)
node2 = Node(2,2)
nodes = [node1, node2]  # I actually don't know if I should create a 
                        # list of nodes so please tell me if I should 
                        # not
### CODE TO SOLVE THE PROBLEM ###

在这种情况下,node1 和节点 2 之间的最低 fcost 是节点 2 的 fcost,因此我希望输出为: (2,2)[2,2]无论是列表还是元组,无论哪种方式都可以。

您应该使用 min() 函数。你可以以不同的方式使用它,但在这种情况下,我认为最简单的解决方案是使用 lambda 函数 - 这是在 python 中编写和定义函数的较短方法。您可以在此处阅读有关 min() 函数的更多信息,并在此处阅读有关 lambda 函数的更多信息。

无论如何,这段代码应该可以正常工作:

class Node():
# Node class
def __init__(self, y, x):
    self.y = y
    self.x = x        
def gcost(self):
    return self.x + self.y
def hcost(self):
    return self.x * self.y
def fcost(self):
    return self.gcost() + self.hcost()
node1 = Node(5,5)
node2 = Node(2,2)
nodes = [node1, node2]
needed_node = min(nodes, key=lambda x:x.fcost())
needed_list = [needed_node.x, needed_node.y]  # in case you want the result as a list
needed_tuple = (needed_node.x, needed_node.y)  # in case you want the result as a tuple

使用 min(list, key=...)

min_node = min(nodes, key=lambda n:n.fcost())
print(min_node, min_node.fcost(), min_node.x, min_node.y)

key必须是函数的名称。

min将使用它来获取值,它将比较该值以找到最小的值。

最新更新