从列表添加边缘时,如何阻止Networkx更改边缘的顺序? [英] How to stop Networkx from changing the order of edges when adding them from a list?

查看:207
本文介绍了从列表添加边缘时,如何阻止Networkx更改边缘的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在NetworkX(python)中将列表中的边添加到图形中会更改边的顺序,这在绘制图形时给我带来了问题. 例如:

Adding edges from a list to a graph in NetworkX (python) changes the order of the edges, which causes problems for me when drawing the Graph. As example:

import networkx as nx

airports = ['A','B','C']
edgelst  = [['C','B'],['A','B'],['A','C']]

G = nx.Graph()

G.add_nodes_from(airports)
G.add_edges_from(edgelst)

如果我检查网络中的现有边缘,则结果如下:

This is the result if I check for the existing edges in the network:

>>> G.edges()
[('A', 'C'), ('A', 'B'), ('C', 'B')]

NetworkX已按字母顺序对边缘进行排序,但我只希望它们与edgelst的顺序相同.我该怎么办?

NetworkX has sorted the edges alphabetically, but I just want them to be in the same order as edgelst. How could I accomplish this?

推荐答案

您的问题的答案有点混乱,因为NetworkX Graph类未保留边缘中节点的顺序.但是,可以通过对每个边进行排序以保证节点顺序来避免这种情况. G.edges()也可以通过自定义键进行排序,该自定义键检索每个边出现在边列表中的索引.

The answer to your question is a bit messy because the NetworkX Graph class doesn't retain the order of nodes in an edge. However, this can be circumvented by sorting each edge to guarantee node order. G.edges() can also be sorted by a custom key that retrieves the index that each edge appears in the edge list.

import networkx as nx

edgelist  = [['C','B'],['A','B'],['A','C']]

首先,对每个边缘中的节点进行排序,并创建一个字典,将每个边缘映射到边缘列表中的索引:

First, sort the nodes in each edge and create a dictionary that maps each edge to its index in the edge list:

edgelist = [sorted(edge) for edge in edgelist]
mapping = {tuple(edge): index for (edge, index) in zip(edgelist, range(len(edgelist)))}

然后根据边缘列表中的索引边缘对图形边缘的顺序进行排序:

Then sort the order of the graph's edges according to the index edges in the edge list:

G = nx.Graph()
G.add_edges_from(edgelist)
sorted(G.edges(), key=lambda edge: mapping[tuple(sorted(list(edge)))])

这篇关于从列表添加边缘时,如何阻止Networkx更改边缘的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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