1

我使用 pygraphviz 生成以下图表:

graph "Multiport-Switches" {
    node [color="#dddddd",
            label="\N",
            shape=record,
            style=filled
    ];
    Switch0  [label="<1> 1|<2> 2|<3> 3|<4> 4|<5> 5|<6> 6|<7> 7|<8> 8"];
    Switch1  [label="<1> 1|<2> 2|<3> 3|<4> 4|<5> 5|<6> 6|<7> 7|<8> 8"];
    Switch0:1 -- Switch1:1;
    Switch0:2 -- Switch1:2;
    Switch0:3 -- Switch1:3;
    Switch0:4 -- Switch1:4;
    Switch0:5 -- Switch1:5;
    Switch0:6 -- Switch1:6;
    Switch0:7 -- Switch1:7;
    Switch0:8 -- Switch1:8;
}

如果我遍历边缘,我可以使用以下代码查看所有边缘:

for edge in G.edges():
    print edge, edge.attr

正如您在下面的输出中看到的那样,边缘元组是“相同的”,但它们仍然由属性区分。如果我想选择一个特定的,我可以在迭代时比较每个边的不同的特定属性。

(u'Switch0', u'Switch1') {u'tailport': u'1', u'headport': u'1'}
(u'Switch0', u'Switch1') {u'tailport': u'2', u'headport': u'2'}
(u'Switch0', u'Switch1') {u'tailport': u'3', u'headport': u'3'}
(u'Switch0', u'Switch1') {u'tailport': u'4', u'headport': u'4'}
(u'Switch0', u'Switch1') {u'tailport': u'5', u'headport': u'5'}
(u'Switch0', u'Switch1') {u'tailport': u'6', u'headport': u'6'}
(u'Switch0', u'Switch1') {u'tailport': u'7', u'headport': u'7'}
(u'Switch0', u'Switch1') {u'tailport': u'8', u'headport': u'8'}

现在,如果我使用以下代码来获得优势:

edge = G.get_edge('Switch0', 'Switch1')
print edge, edge.attr

我只得到最后一条('Switch0', 'Switch1')边,如下所示:

(u'Switch0', u'Switch1') {u'tailport': u'8', u'headport': u'8'}

(u'Switch0', u'Switch1')除了最后一条边之外,有什么方法可以在不遍历所有边的情况下获得特定的边?通过在类似get_edge或类似的方法中传递额外的属性参数可能吗?

4

1 回答 1

1

根据此处的文档,我找到了一个看起来像是建议的解决方案:The optional key argument allows assignment of a key to the edge. This is especially useful to distinguish between parallel edges in multi-edge graphs (strict=False).

创建边时,该add_edge方法有一个可选Key参数,None默认设置为。如果提供了唯一键,则Key可以在用于get_edge检索边缘时使用它。所以如果我用这样的代码创建边缘:

# The for-loop will run from 1-8
for port in range(1, 9):
    G.add_edge('Switch0', 'Switch1', key="{}-{}".format(port, port), headport = port, tailport = port)

然后我可以通过传递我之前以独特方式生成的密钥来检索特定的边:

for port in range(1, 9):
    edge = G.get_edge('Switch0', 'Switch1', key="{}-{}".format(port, port))
    print edge, edge.attr
于 2015-02-15T00:30:05.037 回答