如何检查如果边缘有Networkx属性

如何检查如果边缘有Networkx属性

本文介绍了如何检查如果边缘有Networkx属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个YED图,我要检查,如果边缘有一个属性。例如一些边缘具有一个标签,但一些不。当我尝试这样做,我得到一个错误:

I created a graph in yEd and I want to check if an edge has an attribute. For example some edges have a label but some dont. When I try to do this I get an an error:

for n, nbrs in G.adjacency_iter():
  for nbr,eattr in nbrs.items():
    evpn = eattr['vpn']
    elabel = eattr['label']  #error is here
    if evpn != "No":
      nlabel = G[n].get("label")
      platform = G[n].get("platform")
      if G[nbr].get("platform") == platform:
        g_vpn.add_nodes_from([n,nbr], label, platform) # I dont know if this way
                                                 #to set attributes is right

虽然VPN属性的作品,因为我已经设置的默认值。我知道我可以只是把一个标签值在所有边缘,但我想我的程序检查,如果标签丢失,并设定像我下面做什么的默认值。虽然这是行不通的,因为它不能在一些边找到标签属性:

While vpn attribute works because I have set a default value. I know I could just put a label value in all edges but I want my program to check if label is missing and setting a default value like what I do below. Although it doesn't work because it can't find the label attribute in some edges:

for e,v in G.edges():
  if G[e][v].get("label") == ""
  label = "".join("vedge",i)
  i+=1
  G[e][v]['label']=label

此外,如果你可以检查code的休息,告诉我,如果需要任何改进或做出一些事情更容易做。谢谢

Also if you could check the rest of that code and tell me if it needs any improvement or make some things easier to do. Thanks

推荐答案

边缘属性被存储为一个字典,所以你可以测试一下,看看如果键在字典:

The edge attributes are stored as a dictionary so you can test to see if the key is in the dictionary:

In [1]: import networkx as nx

In [2]: G = nx.Graph()

In [3]: G.add_edge(1,2,color='blue')

In [4]: G.add_edge(2,3)

In [5]: 'color' in G[1][2]
Out[5]: True

In [6]: 'color' in G[2][3]
Out[6]: False

这篇关于如何检查如果边缘有Networkx属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 04:54