[英]Networkx Python Edges Comparison
我一直在嘗試為項目構建圖形,並且在嘗試向其添加更多信息后識別新添加的邊。
例如,在下面的示例中,您可以看到其第一次和第二次迭代:
----------------------一般信息圖H ------------------------ -----
Total number of Nodes in Graph: 2364
Total number of Edges: 3151
----------------------常規信息圖G ------------------------ -----
Total number of Nodes in Graph: 6035
Total number of Edges: 11245
我遇到的問題是當我嘗試使用代碼來識別新添加的邊緣時:
counter = 0
edges_all = list(G.edges_iter(data=True))
edges_before = list(H.edges_iter(data=True))
print "How many edges in old graph: ", len(edges_before)
print "How many edges in new graph: ", len(edges_all)
edge_not_found = []
for edge in edges_all:
if edge in edges_before:
counter += 1
else:
edge_not_found.append(edge)
print "Edges found: ", counter
print "Not found: ", len(edge_not_found)
我一直得到這些結果:
How many edges in old graph: 3151
How many edges in new graph: 11245
Edges found: 1601
Not found: 9644
我不明白為什么找到1601而不是11245-3151 = 8094
有任何想法嗎?
謝謝!
TL / DR:對於您所看到的內容,有一個簡單的解釋,如果您最終使用的話,則可以使用更短的方法來編寫代碼(此過程中有很多解釋)。
首先要注意的是, Edges found
似乎是H
和G
Edges found
數量。 因此,它應該只包含3151,而不是8094。應該Not found
8094。 請注意,找到的邊數1601大約是您期望數的一半。 這是有道理的,因為:
我相信您遇到的問題是,當networkx列出邊緣時,邊緣可能在edges_before
顯示為(a,b)
。 但是,在edges_after
,它可能會在列表中顯示為(b,a)
。
因此(b,a)
不會在edges_before
。 它將使您的測試失敗。 假設在為H
和G
列出邊緣順序時它們之間不相關,那么您期望找到其中一半通過。 您可以進行其他測試以查看(b,a)
是否為H
的邊。 這是H.has_edge(b,a)
一個直接的改進:
for edge in edges_all:
if H.has_edge(edge[0],edge[1]):
counter += 1
else:
edge_not_found.append(edge)
這樣,您甚至可以避免定義edges_before
。
您還可以通過更好的改進來避免定義edges_all
:
for edge in G.edges_iter(data=True):
if H.has_edge(edge[0],edge[1]):
etc
注意:我已將其寫為H.has_edge(edge[0],edge[1])
來說明正在發生的事情。 編寫它的更復雜的方法是H.has_edge(*edge)
。 *edge
表示法將元組解包 。
最后,使用列表推導提供了一種更好的獲取edge_not_found的方法:
edge_not_found = [edge for edge in G.edges_iter(data=True) if not H.has_edge(*edge)]
這將創建一個由edge
s組成的列表,這些edge
在G
但不在H
。
將所有這些放在一起(並使用.size()
命令對網絡中的邊緣進行計數),我們得到了一個更干凈的版本:
print "How many edges in old graph: ", H.size()
print "How many edges in new graph: ", G.size()
edge_not_found = [edge for edge in G.edges_iter(data=True) if not H.has_edge(*edge)]
print "Not found: ", len(edge_not_found)
print "Edges found: ", G.size()-len(edge_not_found)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.