微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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,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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。