子圖 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()