问题描述
以下问题是使用 Python 3.9 和 Networkx 2.5
我需要输出一个 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,i)])
输出: {'重量':88}
解决方法
我希望函数的输入是 ('Rochester,NY','Seattle,WA'),输出是 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,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,WA')
combined_neighbors = set(n1) | set(n2)
common_neighbors = set(n1) & set(n2)