2016-12-07 6 views
1

無向グラフでは、エッジは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)] 

あるエッジに対して異なる表現を避けるために(手選別を含まない)方法がある:ここで私が参照してる何の小さな例はありますか?

答えて

0

タイトルでは順序付きの辺を求めていますが、あなたの例では、辺の順序付きノードを求めているので、あなたが何を望んでいるのか分かりません。私の例では、両方の注文を示しています。リストの理解を使用してエッジの新しいリストを作成することに注意してください。オリジナルのエッジリスト(some_edges)は変更されていません。

最初に、エッジのリスト内のノードの個々のタプルをソートする方法。つまり、エッジは同じ順序ですが、ノードはソートされます。

これで、エッジのリストでエッジを並べ替える方法を説明しました。上記のコードの両方のブロックのための

# 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)] 
関連する問題