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

时间:2018-05-03 15:16:37

标签: python-2.7 networkx neighbours

此问题设置是python 2.7,使用包networkx:https://networkx.github.io/documentation/stable/reference/classes/generated/networkx.Graph.neighbors.html

我正在寻找一种方法来使用“networkx.Graph.neighbors”函数,该函数返回所有具有一定权重值(或高于/低于某个值)的邻居。

有什么建议我可以做到这一点吗?

提前谢谢:)。 添

2 个答案:

答案 0 :(得分:2)

让我们假设你想要过滤' c'节点邻居根据权重。创建以下图表:

    G = nx.Graph()
    G.add_edge('a', 'b', weight=0.6)
    G.add_edge('a', 'c', weight=0.2)
    G.add_edge('c', 'd', weight=0.1)
    G.add_edge('c', 'e', weight=0.7)
    G.add_edge('c', 'f', weight=0.9)
    G.add_edge('a', 'd', weight=0.3)

    list_neighbors=G.neighbors('c')
    for i in list_neighbors:
        if G.edges[('c',i)]['weight']>0.5:
            print (G.edges[('c',i)])

给出: {'体重':0.7} {'体重':0.9} 希望这能回答你的问题。 如果您需要有关如何使用权重的更多信息,请参阅链接。 https://networkx.github.io/documentation/stable/auto_examples/drawing/plot_weighted_graph.html

答案 1 :(得分:1)

我将假设"所有具有一定重量值的邻居"指节点权重。我将通过示例查找权重大于特定值的邻居。

import networkx as nx
import random

G = nx.Graph()

#now create nodes with random weights.  If this notation is
#unfamiliar, read up on list comprehensions.  They make life much easier.
nodes = [(node, {'weight':random.random()}) for node in range(10)]
G.add_nodes_from(nodes)

#now G has the nodes and they each have a random weight.
G.nodes(data=True)
> [(0, {'weight': 0.42719462610483916}),
 (1, {'weight': 0.13985473528922154}),
 (2, {'weight': 0.06889096983404697}),
 (3, {'weight': 0.10772762947744585}),
 (4, {'weight': 0.24497933676194383}),
 (5, {'weight': 0.18527691296273396}),
 (6, {'weight': 0.16379510964497113}),
 (7, {'weight': 0.5481883941716088}),
 (8, {'weight': 0.3782931298078134}),
 (9, {'weight': 0.5902126428368549})]

#now create edges from 0 to all other nodes
zero_edges = [(0,u) for u in range(1,10)]
G.add_edges_from(zero_edges)

#now find all neighbors of 0 with weight > 0.5
heavy_neighbors = [nbr for nbr in G.neighbors(0) if G.node[nbr]['weight']>0.5]
heavy_neighbors
>[7,9]

如果您愿意,还可以通过将heavy_neighbors[替换为](来使)成为生成器。

相关问题