Networkx 节点和边缘索引和属性

Networkx node and edge indices and attributes

import networkx as nx

G = nx.DiGraph()
source = 0
target = 1
G.add_node(source, name='Ham')
G.add_node(target, name='Eggs')
G.add_edge(source, target, meal='Breakfast')
nodes = G.nodes(data=True)

for src, tgt, attr in G.edges(data=True):
    # print type(node1)
    src_id, src_attr = nodes[src]
    tgt_id, tgt_attr = nodes[tgt]
    print(str(src) + ' - ' + str(tgt) + ' : ' + attr['meal']
          + ' : ' + src_attr['name'] + ' , ' + tgt_attr['name'])

上面的代码产生了所需的正确输出:

0 - 1 : Breakfast : Ham , Eggs

但是代码是错误的。您可以通过将 0/1 替换为 5/7 来查看代码错误。

小问题

如果我们使用 source = 5target = 7 而不是 source = 0target = 1,我们如何继续获得输出 Breakfast : Ham , Eggs

长问题

我也在寻找这些问题的答案,以便更好地理解为什么您对这个简短问题的解决方案有效。

您可以通过 G.node:

访问节点的属性
for src, tgt, attr in G.edges(data=True):
    # print type(node1)
    src_attr = nodes[src]
    tgt_attr = nodes[tgt]
    print(str(src) + ' - ' + str(tgt) + ' : ' + attr['meal']
          + ' : ' + src_attr['name'] + ' , ' + tgt_attr['name'])

在for循环中,srctgt是节点names/identifiers。 networkx 没有节点对象的概念,它直接操作names/identifiers。


G.nodes(data=True)返回的列表长度等于节点数。 由于节点 names/identifiers 可以是任意类型,如果 x 是字符串,则创建大小为 x 的列表没有意义。

这里有一个字符串的例子是节点names/identifiers:

import networkx as nx

G = nx.DiGraph()
source = 'foo'
target = 'bar'
G.add_node(source, name='Ham')
G.add_node(target, name='Eggs')
G.add_edge(source, target, meal='Breakfast')

for src, tgt, attr in G.edges(data=True):
    # print type(node1)
    src_attr = G.node[src]
    tgt_attr = G.node[tgt]
    print(str(src) + ' - ' + str(tgt) + ' : ' + attr['meal']
          + ' : ' + src_attr['name'] + ' , ' + tgt_attr['name'])

它输出这个:

foo - bar : Breakfast : Ham , Eggs