[英]Python - Networkx: Graph of Neighbor Nodes with certain weight
以下問題是使用 Python 3.9 和 Networkx 2.5
我需要 output G 的子圖,它只包含列表中節點之間的邊以及邊權重小於 100 的直接相鄰節點。目前我正在使用以下代碼,但只能拉邊權重。 我需要同時獲取節點名稱和邊權重。
list_neighbors=G.neighbors('Rochester, NY')
for i in list_neighbors:
if G.edges[('Rochester, NY',i)]['weight']<100:
print (G.edges[('Rochester, NY',i)])
OUTPUT:{'重量':88}
如何讓 output 也包含節點名稱(輸入節點及其符合權重標准的鄰居)
我想讓 function 的輸入為('Rochester, NY', 'Seattle, WA')和 output 成為 100 英里內的每個相鄰城市。
不鼓勵跟進問題以支持新的、單獨的問題,但由於您是新來的:
import networkx as nx
# version 1 : outputs an iterator; more elegant, potentially more performant (unlikely in this case though)
def get_neighbors_below_threshold(graph, node, threshold=100, attribute='weight'):
for neighbor in graph.neighors(node):
if graph.edges[(node, neighbor)][attribute] < threshold:
yield neighbor
# version 2 : outputs a list; maybe easier to understand
def get_neighbors_below_threshold(graph, node, threshold=100, attribute='weight'):
output = []
for neighbor in graph.neighors(node):
if graph.edges[(node, neighbor)][attribute] < threshold:
output.append(neighbor)
return output
n1 = get_neighbors_below_threshold(G, 'Rochester, NY')
n2 = get_neighbors_below_threshold(G, 'Seattle, WA')
combined_neighbors = set(n1) | set(n2)
common_neighbors = set(n1) & set(n2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.