开始使用免费开始使用

可视化连通性

本练习将可视化最高连通节点的连通性如何随时间变化。上一题已加载了最高连通值列表 top_connected

还记得您在第 1 章使用过的 defaultdict 吗?本题也会再次用到它!正如 Eric 在视频中提到的,这里更推荐使用 defaultdict,因为如果使用普通的 Python 字典,当您尝试用不存在的键取值时会抛出 KeyError

本题将使用嵌套的 for 循环。也就是说,您会在一个 for 循环内部再写一个 for 循环。

本练习是课程的一部分

Python 网络分析中级

查看课程

练习说明

  • 初始化一个名为 connectivity 的空列表 defaultdict
  • 使用 for 循环遍历 top_connected,并在这个外层 for 循环体内再次遍历 Gs。在内层循环中:
    • connectivity 的键应是 top_connected 中的节点 n,值应是连通性分数列表。因此,需要将 len(list(G.neighbors(n))) 追加到 connectivity[n] 中。
  • 使用 .items() 遍历 connectivity,并将 conn 传入 plt.plot() 来绘制每个节点的连通性。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Import necessary modules
import matplotlib.pyplot as plt
from collections import defaultdict

# Create a defaultdict in which the keys are nodes and the values are a list of connectivity scores over time
connectivity = ____
for n in ____:
    for g in ____:
        connectivity[____].____(len(____))

# Plot the connectivity for each node
fig = plt.figure() 
for n, conn in ____: 
    plt.plot(____, label=n) 
plt.legend()  
plt.show()
编辑并运行代码