我想使用Python中的NetworkX获取k-shell算法最内核中与最高度对应的节点。我尝试使用以下代码获取节点,但遇到错误“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)
您的代码中有一个拼写错误 - 您将变量命名为“shells”,但您尝试使用“k_shells”访问它。
将代码更改为:
# 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)