我有一个图表类,其中包含2d网格上的节点。 我想通过使用比较函数比较一个名为end的相对点来对图中的节点进行排序。 我希望能够在函数内部进行比较,但我很难理解如何将相对点传递给compare函数。
我的代码:
class Graph: def __init__(self, end): self.nodes = set() self.edges = defaultdict(list) self.distances = {} self.end = end def add_node(self, value): self.nodes.add(value) def add_edge(self, from_node, to_node, distance): self.edges[from_node].append(to_node) self.edges[to_node].append(from_node) self.distances[(from_node, to_node)] = distance def compare(node1, node2): d1 = findDist(end, node1) d2 = findDist(end, node2) if d1 < d2: return -1 elif d1 > d2: return 1 else: return 0 def sortPoints(self): sorted(self.edges, key=self.compare)所以比较函数通常得到2个参数,内置的有序函数知道如何使用它。 我认为使用相对点作为类成员,但我再次找不到一种方法来为我的比较函数提供self关键字,并访问它。
有没有什么好方法可以实现这个目标?
I have a graph class that has nodes that are on a 2d grid. I want to sort the nodes in graph by comparing to a relative point, called end, using a compare function. I want to be able to compare inside the function, but I am struggling to understand how I can pass the relative point to the compare function.
My code:
class Graph: def __init__(self, end): self.nodes = set() self.edges = defaultdict(list) self.distances = {} self.end = end def add_node(self, value): self.nodes.add(value) def add_edge(self, from_node, to_node, distance): self.edges[from_node].append(to_node) self.edges[to_node].append(from_node) self.distances[(from_node, to_node)] = distance def compare(node1, node2): d1 = findDist(end, node1) d2 = findDist(end, node2) if d1 < d2: return -1 elif d1 > d2: return 1 else: return 0 def sortPoints(self): sorted(self.edges, key=self.compare)So a compare function usually gets 2 parameters and the built in sorted function knows how to use it. I thought using the relative point as a class member, but again I couldn't find a way to give my compare function the self keyword, and access it.
Is there any good way to achieve this goal?
最满意答案
由于你想使用findDist的返回值作为键,你可以使findDist成为Graph一个方法。 然后你可以将它作为key参数传递给sorted: sorted(self.edges, self.findDist) 。 这是一个如何工作的简化示例:
class Graph: def __init__(self, end): self.end = end def find_dist(self, x): return abs(self.end - x) def sort_values(self, it): return sorted(it, key=self.find_dist) g = Graph(10) print(g.sort_values(range(5, 15)))输出:
[10, 9, 11, 8, 12, 7, 13, 6, 14, 5]Since you want to use the return value of findDist as a key you could make findDist a method of Graph. Then you could pass it as key parameter to sorted: sorted(self.edges, self.findDist). Here's a simplified example on how it would work:
class Graph: def __init__(self, end): self.end = end def find_dist(self, x): return abs(self.end - x) def sort_values(self, it): return sorted(it, key=self.find_dist) g = Graph(10) print(g.sort_values(range(5, 15)))Output:
[10, 9, 11, 8, 12, 7, 13, 6, 14, 5]更多推荐
发布评论