python - 连接相反的节点

标签 python python-2.7 networkx

我在networkx中有两个长度相等且彼此平行的线图,我如何循环这些图并用两条边连接相对的节点,即连接2和2a、3和3a等

nodes1 = [2,5,7,8,9,10]

nodes2 = ['2a','5a','7a','8a','9a','10a']

我试过了

for k in range (0, len(nodes1)):
    for i in range (0, len(nodes2)):
        if nodes1.index(kk) == nodes2.index(i):
            X.add_edge(k,i)

但它没有给出所需的输出,请任何人纠正我。谢谢

               This is what I have 
          2---------3---------4----------5----------6



          2a---------3a-------4a--------5a---------6a


                 This is what I want 
            2---------3---------4----------5-----------6
            ||        ||        ||         ||         ||
            ||        ||        ||         ||         ||
            ||        ||        ||         ||         ||
           2a--------3a---------4a---------5a---------6a

抱歉,如果之前的帖子不清楚

最佳答案

您的代码无法按原样工作的原因是,索引返回值所在列表中的索引,因此您从 0 循环到每个列表的长度和第一个值您的列表中不存在 0,这会引发 ValueError。请参阅在线文档:http://docs.python.org/2/tutorial/datastructures.html

如果您只想创建元组对并假设长度和顺序已经正确,那么如果您使用此行修改代码:

for k in range (0, len(nodes1)):
    X.add_edge(nodes1[k],nodes2[k])

会实现你想要的,因为你想并行遍历两个列表,即使index没有引发ValueError,你的原始代码也会导致5 x 5 条目,因为您为 node1 中的每个节点添加 nodes2 中的每个条目的边,这不是您想要的。

假设您的两个列表的排序匹配,那么您可以进行列表理解来创建边缘列表并从中创建图表

In [171]:

edge_list = [(nodes1[i], nodes2[i]) for i in range(len(nodes1))]
# I'm using python 3 so you could do the following also
# edge_list = list(zip(nodes1, nodes2))
G=nx.DiGraph()
G.add_edges_from(edge_list)
G.edges()
Out[171]:
[(2, '2a'), (5, '5a'), (7, '7a'), (8, '8a'), (9, '9a'), (10, '10a')]

编辑

如果你想在两个方向上添加边缘,那么你只需通过交换列表的顺序来创建一个辅助的edge_list:

In [194]:

edge_list_reversed = list(zip(nodes2, nodes1))
edge_list_reversed
G.add_edges_from(edge_list_reversed)
G.edges()
Out[194]:
[(2, '2a'),
 (5, '5a'),
 (7, '7a'),
 (8, '8a'),
 (9, '9a'),
 (10, '10a'),
 ('2a', 2),
 ('8a', 8),
 ('9a', 9),
 ('5a', 5),
 ('10a', 10),
 ('7a', 7)]

关于python - 连接相反的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22711695/

相关文章:

javascript - 输入后网页不刷新

python - Python 2 中的 TicTacToe 项目 : I am trying to avoid using global variables and return variables instead

python - 在 Networkit 中检索原始节点名称

python - 如何将数据暴露给zabbix

python - 如何使用 Flask 和 WTForms 在保留表单数据的同时进行重定向?

python - Tcl 错误 : bad geometry specifier

python - 使用 networkx 更新图的边属性

python - NetworkX 图形对象不可订阅

python - 阅读文档搜索损坏

python - 找出段落中出现的单词