【问题标题】:Networkx neighbor set not printingNetworkx 邻居设置不打印
【发布时间】:2018-04-20 01:05:14
【问题描述】:

我的 networkx 代码有点问题。 我试图从图中的一个节点中找到所有邻居,但是....

neighbor = Graph.neighbors(element)
print(neighbor)

输出:

<dict_keyiterator object at 0x00764BA0>

而不是我应该得到的所有邻居......我的一个朋友,他使用的是旧版本的 networkx 没有得到这个错误,他的代码完全相同并且运行良好。

谁能帮我?降级我的networkx不是一种选择。

编辑:

这是我的完整代码

Graph = nx.read_graphml('macbethcorrected.graphml')    
actors = nx.nodes(Graph)

for actor in actors:
    degree = Graph.degree(actor)
    neighbor = Graph.neighbors(actor)
    print("{}, {}, {}".format(actor, neighbor, degree))

这是我正在使用的图表: http://politicalmashup.nl/new/uploads/2013/09/macbethcorrected.graphml

【问题讨论】:

标签: python-3.x graph nodes networkx


【解决方案1】:

从 networkx 2.0 开始,Graph.neighbors(element) 返回一个迭代器而不是一个列表。

要获取列表,只需申请list

list(Graph.neighbors(element))

或使用列表推导:

neighbors = [n for n in Graph.neighbors(element)]

第一种方法(首先由Joel 提到)是推荐的方法,因为它更快。

参考:https://networkx.github.io/documentation/stable/reference/classes/generated/networkx.Graph.neighbors.html

【讨论】:

    【解决方案2】:

    正如其他人所指出的,在 networkx 2.0 neighbors 返回一个迭代器而不是一个列表。 Networkx 提供了一个用 1.x 到 2.0 编写的guide for migrating code。对于neighbors,推荐

    list(G.neighbors(n))
    

    (请参阅Fastest way to convert an iterator to a list)。迁移指南提供了示例:

    >>> G = nx.complete_graph(5)
    >>> n = 1
    >>> G.neighbors(n)
    <dictionary-keyiterator object at ...>
    >>> list(G.neighbors(n))
    [0, 2, 3, 4]
    

    【讨论】:

      【解决方案3】:

      你可以为此制定方法,

      def neighbors(G, n):
      """Return a list of nodes connected to node n. """
      return list(G.neighbors(n))
      

      并将该方法称为:

      print(" neighbours = ", neighbors(graph,'5'))
      

      其中 5 是图中的节点,

      graph = nx.read_edgelist(path, data = (('weight', float), ))
      

      并且路径变量包含数据集文件路径值,其中数据在更多数量的节点和边中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-16
        • 1970-01-01
        • 2018-07-19
        • 1970-01-01
        • 2018-08-04
        • 1970-01-01
        • 1970-01-01
        • 2011-05-14
        相关资源
        最近更新 更多