修复无向网络x图中边的排序

时间:2016-12-07 23:07:26

标签: python networkx

在无向网络X图形中,边缘表示为Python元组。他们的排序取决于你要求他们的方式。这是我所指的一个小例子:

import networkx as nx
g = nx.complete_bipartite_graph(2,2)
print(g.edges())
print(g.edges(2))

输出

[(0, 2), (0, 3), (1, 2), (1, 3)]
[(2, 0), (2, 1)]

是否有办法(不涉及手动排序)以避免对边缘有不同的表示?

1 个答案:

答案 0 :(得分:0)

我不确定你想要什么,因为在你要求有序边缘的标题中,但在你的例子中,你要求边缘有序的节点。在我的例子中,我展示了两者的排序。请注意,我使用列表推导来创建新的边缘列表 - 边缘的原始列表(some_edges)保持不变。

首先,如何对边缘列表中的单个节点元组进行排序。也就是说,边缘的顺序相同,但它们中的节点是按顺序排列的。

import networkx as nx
g = nx.Graph()
g.add_edges_from([
    (5, 2),
    (2, 1),
    (3, 2),
    (4, 2)
])
some_edges = g.edges(2)
print("Not sorted:  ", some_edges)

print("SORTED")
# sort nodes in edges
some_edges_1 = [tuple(sorted(edge)) for edge in some_edges]
print("Sorted nodes:", some_edges_1)

现在如何对边缘列表中的边缘进行排序。

# sort edges in list of edges
some_edges_2 = sorted(some_edges_1)
print("Sorted edges:", some_edges_2)

上述两个代码块的输出:

Not sorted:   [(2, 1), (2, 3), (2, 4), (2, 5)]
SORTED
Sorted nodes: [(1, 2), (2, 3), (2, 4), (2, 5)]
Sorted edges: [(1, 2), (2, 3), (2, 4), (2, 5)]

这里也是反向排序的一个例子,你可以实际看到排序单个边缘和排序边缘列表之间的区别。

print("Not sorted:  ", some_edges)
print("SORTED REVERSE")
# sort nodes in edges
some_edges_1 = [tuple(sorted(edge, reverse=True)) for edge in some_edges]
print("Sorted nodes:", some_edges_1)
# sort edges in list of edges
some_edges_2 = sorted(some_edges_1, reverse=True)
print("Sorted edges:", some_edges_2)

输出:

Not sorted:   [(2, 1), (2, 3), (2, 4), (2, 5)]
SORTED REVERSE
Sorted nodes: [(2, 1), (3, 2), (4, 2), (5, 2)]
Sorted edges: [(5, 2), (4, 2), (3, 2), (2, 1)]