简体   繁体   English

如何使用python字典保存图形边缘权重

[英]how Can I Use python dictionary to save graph edge weight

i want to save graph edge weight my input is something like this 我想保存图形边缘权重,我的输入是这样的

[['A', 'B', '5']]

it means we have edge from 'A' to 'B' with weight 5 这意味着我们从'A'到'B'的权重为5

and my code is 我的代码是

def inputFormatter(array):

    Nodes={}

    for p in array:

        a=p[0]
        b=p[1]
        value=p[2]

        if(a not in Nodes):
            Nodes[a]=NodeInfo(a)

        if(b not in Nodes[a].neighbors):
            Nodes[a].neighbors[b]=value


        if(b not in Nodes):
            Nodes[b]=NodeInfo(b)

        if(a not in Nodes[b].neighbors):
            Nodes[b].neighbors[a]=value

    return Nodes

my NodeInfo Class is 我的NodeInfo类是

class NodeInfo:

    neighbors={}
    nodeName=""

    def __init__(self, nodeName):
        self.nodeName=nodeName

but in printing neighbors key with this code 但是在用此代码打印邻居密钥时

for node in Nodes:
    print node.nodeName +"\t"+ str(node.neighbors.keys())

i see this 我看到这个

A   ['A', 'B']
B   ['A', 'B']

why? 为什么? what's wrong? 怎么了? How Can i Fix this? 我怎样才能解决这个问题?

Your neighbors are a class variable so they are shared in between instances. 您的neighbors是一个类变量,因此它们在实例之间共享。 You should try: 你应该试试:

class NodeInfo:
    def init(self, nodeName):
        self.nodeName = nodeName
        self.neighbors = {}

Note that you're overriding the class member nodeName with an instance member when you do self.nodeName = nodeName (which is why you don't see that they share it). 请注意,在执行self.nodeName = nodeName时,您将使用实例成员覆盖类成员nodeName (这就是为什么看不到它们共享它的原因)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM