获取其值与给定值匹配的类对象

时间:2018-09-23 06:33:07

标签: python

我关注了class-

class GraphClass ():
    def __init__(self, node, neighbours = [], prev_node='', dist = 0):
        self.node = node
        self.neighbours = neighbours
        self.dist = dist
        self.prev_node = prev_node

我将该类的对象定义为-

graph = [GraphClass ('A', ['B','C']), GraphClass ('B', ['D','E']), GraphClass ('C', ['B','F']), GraphClass ('D', ['F','G']), GraphClass ('E', ['G']), GraphClass ('F', ['G']), GraphClass ('G', [])]

如何获取节点为'B'的对象?

当前,我正在执行-

v = [p for p in graph if p.node == 'B'][0]

如您所见,我正在创建一个只有一个条目的list,并通过其index进行选择。有更好的方法吗?

0 个答案:

没有答案