可视化连通性
本练习将可视化最高连通节点的连通性如何随时间变化。上一题已加载了最高连通值列表 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()