3

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

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

有什么建议可以让这成为可能吗?

提前致谢 :)。蒂姆

4

2 回答 2

3

假设您要根据权重过滤“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)])

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

于 2018-05-03T17:05:53.807 回答
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]

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

于 2018-05-03T18:18:36.907 回答