2015-11-03 156 views
1

我的节点有一个由逗号分隔的属性列表,我希望networkx比较它们,如果它们匹配,则在节点之间创建一条边。NetworkX:将边缘添加到节点属性的图形中

这就像我得到,但它不工作,关于如何改进我的方法的任何想法?

for node in G.nodes(): 
    while len(G.node[n]['attr']) = (G.node[n+1]['attr']): 
     # compare attributes? 
     valid_target_found = False 
      while not valid_target_found: 
       target = random.randint(0,N-1) 
       # pick a random node 
       if (not target in G.node[n]['attr']) 
         and len(G.node[n]['attr']) = (G.node[n+1]['attr']): 
         valid_target_found = True 
      G.add_edge(node, target) 

一个或一个以上的参数可以匹配,但只有一个是需要建立一个边缘

+0

你能解释一下你的意思是“匹配”?一个属性匹配计数?都必须匹配?还有别的吗? – Joel

+0

如果其中一个属性是相同的,例如,在'node1'和'node30'中的属性列表中,具有相同的属性,因此应该有一个边 – Chris

回答

1

假设你有一个无向图,这可以用于

import networkx as nx 

G = nx.Graph() 
G.add_node('a', {'k': 1, 'b': 2}) 
G.add_node('b', {'x': 1, 'z': 2}) 
G.add_node('c', {'y': 1, 'x': 2}) 

for node_r, attributes in G.nodes(data=True): 
    key_set = set(attributes.keys()) 
    G.add_edges_from([(node_r, node) for node, attributes in G.nodes(data=True) 
         if key_set.intersection(set(attributes.keys())) 
         and node != node_r]) 

print(G.edges()) 
相关问题