0
我有一個圖G,我首先用一組規則構造所有邊,然後我想隨機刪除它們中的一些。 (每個節點都有一個屬性「標籤」,創建時所有邊都具有賦予的權重屬性。)如何正確訪問Networkx中的邊緣屬性
我在Python 3.4.2上使用Networkx 1.9.1。
以下代碼是我一直試圖做到目前爲止,我打算從節點刪除邊緣,如果其度數高於閾值max_degree。
import networkx as nx
import random
G = nx.Graph()
# ...rest of code, adding nodes and edges...
# Remove undesired edges
max_degree = 4
for node in G.nodes():
if nx.degree(G, node) >= max_degree:
node_edges = G.edges([node])
edge_to_remove = random.choice(node_edges)
# Each edge is a tuple (u,v),
# where u and v are nodes in G.
edge_u = G.node[edge_to_remove[0]]
edge_v = G.node[edge_to_remove[1]]
weight_loss = edge_to_remove['weight']
print("Removing edge (weight={2}) from {0} to {1}"
.format(edge_u['label'], edge_v['label'], weight_loss))
G.remove_edges_from([edge_to_remove])
首先,這是行不通的,其次我的膽量告訴我這是麻煩和繁瑣。 tutorial建議下面的代碼是如何訪問邊緣屬性。該文件指向教程,但我沒有這個:
# From tutorial, accessing edge properties:
G.add_edge(1, 2, weight=4.7)
G[1][2]['weight'] = 4.7
G.edge[1][2]['weight'] = 4s
# I'd expect adaption with my code should be
# the following, but alas..
weight_of_edge = G.edge[node_u][node_v]['weight']
請,我會歡迎建議解決方案,我的問題,或更好的方法。
完美,非常感謝。謝謝你的解釋。 – 2015-02-24 22:59:57