繁体   English   中英

通过python中的Networkx获取图中每个节点的度数

[英]Get degree of each nodes in a graph by Networkx in python

假设我有一个如下所示的数据集,它显示了一个无向图:

1   2
1   3
1   4
3   5
3   6
7   8
8   9
10  11

我有一个像这样的python脚本:

for s in ActorGraph.degree():
    print(s)

这是一个由键和值组成的字典,键是节点名称,值是节点的度数:

('9', 1)
('5', 1)
('11', 1)
('8', 2)
('6', 1)
('4', 1)
('10', 1)
('7', 1)
('2', 1)
('3', 3)
('1', 3)

networkx文档中建议使用 values() 来获得节点度。 现在我喜欢只有节点度数的键,我使用脚本的这一部分,但它不起作用并说object has no attribute 'values'

for s in ActorGraph.degree():
        print(s.values())

我该怎么做?

您使用的是 networkx 2.0 版。 从使用改变dictG.degree()使用一个类似字典的(但不是字典) DegreeView 请参阅本指南

要在列表中包含度数,您可以使用列表理解

degrees = [val for (node, val) in G.degree()]

我想添加以下内容:如果您使用nx.Graph()初始化无向图并在之后添加边,请注意 networkx 不保证节点的顺序将被保留——这也适用于degree() 这意味着,如果您使用列表理解方法,则尝试通过列表索引访问度数,这些索引可能与正确的节点不对应。 如果您希望它们对应,则可以执行以下操作:

degrees = [val for (node, val) in sorted(G.degree(), key=lambda pair: pair[0])]

这是一个简单的例子来说明这一点:

>>> edges = [(0, 1), (0, 3), (0, 5), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (2, 5)]
>>> g = nx.Graph()
>>> g.add_edges_from(edges)
>>> print(g.degree())
[(0, 3), (1, 4), (3, 3), (5, 2), (2, 4), (4, 2)]
>>> print([val for (node, val) in g.degree()])
[3, 4, 3, 2, 4, 2]
>>> print([val for (node, val) in sorted(g.degree(), key=lambda pair: pair[0])])
[3, 4, 4, 3, 2, 2]

您还可以使用 dict comprehension 来获取实际的字典:

degrees = {node:val for (node, val) in G.degree()}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM