子图 II
在上一个练习中,我们给了您一组节点,并让您提取它们的邻居。
我们再做一个练习:请提取具有特定元数据属性的节点及其邻居。这将帮助您回顾如何使用列表推导式查找节点。本练习也会强化您组合已有函数的能力。
本练习是课程的一部分
Python 网络分析入门
练习说明
- 使用列表推导式,提取元数据中
'occupation'为'celebrity'的节点及其邻居:- 列表推导式的 输出表达式 为
n,有两个 迭代变量:n和d。 可迭代对象 是T的节点列表(包含元数据,您可以使用data=True指定),条件表达式 是元数据字典d的'occupation'键等于'celebrity'。
- 列表推导式的 输出表达式 为
- 将它们放入名为
T_sub的新子图中。为此:- 遍历这些节点,计算每个节点的邻居,并使用
.union()方法将它们添加到节点集合nodeset中。最后这一步已为您完成。 - 将
nodeset与T.subgraph()方法配合使用以计算T_sub。
- 遍历这些节点,计算每个节点的邻居,并使用
- 将
T_sub绘制到屏幕上。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Extract the nodes of interest: nodes
nodes = [n for n, d in ____ if ____ == ____]
# Create the set of nodes: nodeset
nodeset = set(nodes)
# Iterate over nodes
for n in ____:
# Compute the neighbors of n: nbrs
nbrs = ____
# Compute the union of nodeset and nbrs: nodeset
nodeset = nodeset.union(nbrs)
# Compute the subgraph using nodeset: T_sub
T_sub = ____
# Draw T_sub to the screen
____
plt.show()