NetworkX:从节点属性向图添加边 [英] NetworkX: add edges to graph from node attributes

查看:727
本文介绍了NetworkX:从节点属性向图添加边的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的节点有一个用逗号分隔的服装列表,我希望networkx比较它们,如果它们匹配,则在节点之间创建一条边.

My nodes have a list of attibutes that is seperated by commas, i wanted networkx to compare them and if they match, create an edge between the nodes.

就我所知,但是关于如何改进我的方法的任何想法都行不通?

That is as for as i got, but it's not working, any ideas on how to improve my approach?

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)

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

one or more of the arguments can match, but only one is needed to create an edge

推荐答案

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

assuming you have a undirected graph, this could be used

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

这篇关于NetworkX:从节点属性向图添加边的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆