我想使用Python中的NetworkX获得k-shell算法最内核中对应于最高度的 node .我try 使用以下代码获取 node ,但遇到错误"AttributeError:'DiGraph'对象没有属性'keys'"

# Create a digraph
G = nx.DiGraph()
G.add_edge(1,2,weight=673)  
G.add_edge(2,4,weight=201)  
G.add_edge(4,1,weight=20)  
G.add_edge(2,3,weight=96)  
G.add_edge(3,4,weight=44)  
G.add_edge(6,3,weight=7)  
G.add_edge(6,4,weight=96)  
G.add_edge(5,6,weight=10)  
G.add_edge(7,6,weight=10)  
G.add_edge(8,6,weight=10)  

# Calculate k-shells
shells = nx.algorithms.core.k_shell(g)

# Find the maximum k-shell value
max_k_shell = max(k_shells.keys())

# Get the nodes in the most inner core
inner_core_nodes = k_shells[max_k_shell]

# Print the nodes in the most inner core
print(inner_core_nodes)

推荐答案

k_shell返回子图.

如果不提供k的值,则返回shell (对应于阶数最高的 node ),也可以使用k_core(这两个等同于阶数为k=None的 node ,因为没有阶数更高的 node ):

H = nx.k_shell(G)
# or 
H = nx.k_core(G)

H.nodes
# NodeView((1, 2, 4, 3, 6))

请注意,您也可以使用core_number来获取核心号码并手动筛选这些号码:

d = nx.core_number(G)
max_degree = max(d.values())

nodes = {k for k, v in d.items() if v == max_degree}

输出:{1, 2, 3, 4, 6}

Python相关问答推荐

Python会扔掉未使用的表情吗?

Python多处理:当我在一个巨大的pandas数据框架上启动许多进程时,程序就会陷入困境

即使在可见的情况下也不相互作用

@Property方法上的inspect.getmembers出现意外行为,引发异常

如何使用pandasDataFrames和scipy高度优化相关性计算

如何使用matplotlib在Python中使用规范化数据和原始t测试值创建组合热图?

删除所有列值,但判断是否存在任何二元组

将数据框架与导入的Excel文件一起使用

scikit-learn导入无法导入名称METRIC_MAPPING64'

如何让Flask 中的请求标签发挥作用

Polars:用氨纶的其他部分替换氨纶的部分

Python—从np.array中 Select 复杂的列子集

利用Selenium和Beautiful Soup实现Web抓取JavaScript表

在含噪声的3D点网格中识别4连通点模式

pandas在第1列的id,第2列的标题,第3列的值,第3列的值?

504未连接IB API TWS错误—即使API连接显示已接受''

如何获取包含`try`外部堆栈的`__traceback__`属性的异常

Seaborn散点图使用多个不同的标记而不是点

在Pandas 中以十六进制显示/打印列?

为什么在安装了64位Python的64位Windows 10上以32位运行?