简体   繁体   English

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

[英]Python - Networkx: Graph of Neighbor Nodes with certain weight

The following problem is using Python 3.9 and Networkx 2.5以下问题是使用 Python 3.9 和 Networkx 2.5

I need to output a subgraph of G that only contains edges between nodes in a list and directly neighboring nodes with edge weights less than 100. Currently I am using the following code, but only am able to pull the edge weight.我需要 output G 的子图,它只包含列表中节点之间的边以及边权重小于 100 的直接相邻节点。目前我正在使用以下代码,但只能拉边权重。 I need to get both the node name and edge weight.我需要同时获取节点名称和边权重。

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: {'weight': 88} OUTPUT:{'重量':88}

How do I get the output to include the Node Names as well (input node and it's neighbor that meets criteria of weight)如何让 output 也包含节点名称(输入节点及其符合权重标准的邻居)

I would like to have the input of the function be ('Rochester, NY', 'Seattle, WA'), and the output to be the neighbor cities of each within 100 miles.我想让 function 的输入为('Rochester, NY', 'Seattle, WA')和 output 成为 100 英里内的每个相邻城市。

Follow up questions are discouraged in favour of new, separate question but since you are new here:不鼓励跟进问题以支持新的、单独的问题,但由于您是新来的:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM