開始使用免費開始

子圖 II

在上一個練習中,我們給了你一串節點,並請你取出它們的鄰居。

我們再來做一次類似的練習:這次要你根據節點的特定中介資料屬性,取出這些節點及其鄰居。這會讓你回想先前用列表生成式找節點的方法,也能強化你把已經寫過的函式組合起來的能力。

本練習屬於課程

Python 網路分析入門

檢視課程

練習說明

  • 使用列表生成式,擷取中介資料 'occupation''celebrity' 的節點及其鄰居:
    • 列表生成式的「輸出運算式」為 n,且有兩個「迭代變數」:nd。「可迭代物件」是 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()
編輯並執行程式碼