Python - Networkx:具有一定权重的邻居节点图

时间:2021-05-25 01:53:53

标签: python networkx

以下问题是使用 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, NY',i)])

输出: {'重量':88}

如何让输出也包含节点名称(输入节点及其满足权重标准的邻居)

1 个答案:

答案 0 :(得分:0)

<块引用>

我希望函数的输入是 ('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, 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)