python - NetworkX:从节点属性向图中添加边

标签 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)

一个或多个参数可以匹配,但创建一条边只需要一个

最佳答案

假设您有一个无向图,可以使用它

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())

关于python - NetworkX:从节点属性向图中添加边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33494376/

相关文章:

python - 为什么Python中类属性的赋值行为类似于实例变量的赋值?

javascript - 如何在 JavaScript 中交换 DOM 子节点?

python - Lasso 回归,所有系数均为 0

python - 子进程 stdin PIPE 在程序终止之前不会返回

python - 什么效率更高 : add fields to the message or create a custom header? RabbitMQ

xsd - 如何通过 xs :unique 使我的枚举具有唯一性

python - 从字典创建 Pandas Dataframe 的问题

Python 元素树 : replacing elements in a loop

c++ - 如何删除双向链表中与某个值匹配的所有项?

c++ - 搜索链表是否为空