开始使用免费开始使用

子图 II

在上一个练习中,我们给了您一组节点,并让您提取它们的邻居。

我们再做一个练习:请提取具有特定元数据属性的节点及其邻居。这将帮助您回顾如何使用列表推导式查找节点。本练习也会强化您组合已有函数的能力。

本练习是课程的一部分

Python 网络分析入门

查看课程

练习说明

  • 使用列表推导式,提取元数据中 'occupation''celebrity' 的节点及其邻居:
    • 列表推导式的 输出表达式 为 n,有两个 迭代变量:nd。 可迭代对象 是 T 的节点列表(包含元数据,您可以使用 data=True 指定),条件表达式 是元数据字典 d'occupation' 键等于 'celebrity'
  • 将它们放入名为 T_sub 的新子图中。为此:
    • 遍历这些节点,计算每个节点的邻居,并使用 .union() 方法将它们添加到节点集合 nodeset 中。最后这一步已为您完成。
    • nodesetT.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()
编辑并运行代码