【问题标题】:Python - Networkx: Graph of Neighbor Nodes with certain weightPython - Networkx:具有一定权重的相邻节点图
【发布时间】:2021-08-13 06:32:00
【问题描述】:

以下问题是使用 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}

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

【问题讨论】:

  • 你的变量i应该包含邻居的名字。
  • 扩展@Sparky05' 评论:print(i, G.edges[('Rochester, NY',i)]).
  • @PaulBrodersen 谢谢你的工作。对此的跟进将是 - 我如何将其转换为具有多个城市(节点)输入的函数。例如,我想让函数的输入为 ('Rochester, NY', 'Seattle, WA'),输出为 100 英里内的每个相邻城市。非常感谢任何帮助

标签: python networkx


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2022-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多