NetworkX:从节点属性向图形添加边

时间:2015-11-03 08:24:17

标签: python attributes nodes networkx edges

我的节点有一个由逗号分隔的属性列表,我希望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)

一个或多个参数可以匹配,但创建边

只需要一个

1 个答案:

答案 0 :(得分: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())
相关问题