開始使用免費開始

以時間篩選邊

接下來你要練習在邊上套用條件來篩選圖形。這會幫助你熟悉含有條件的串列生成式,並更順手地使用它們。

在這些練習中,請記得你可以從 datetime 模組匯入 datetime 物件。在圖形中,中介資料有一個 date 鍵,搭配的值是一個 datetime 物件。

本練習屬於課程

Python 網路分析進階

檢視課程

練習說明

  • 建立一個名為 G_sub 的新圖形。
  • 使用 .add_nodes_from() 方法,從原始圖形加入節點(包含節點的中介資料)。
  • 使用含有一個條件的串列生成式來加入邊,條件為邊的日期早於 2004-05-16。作法如下:
    • 使用 .add_edges_from() 方法,並以串列生成式作為引數。
    • 串列生成式的輸出表達式為 (u, v, d)。遍歷 G 的所有邊,並檢查 d['date'] 是否小於 datetime(2004, 5, 16)

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

import networkx as nx
from datetime import datetime

# Instantiate a new graph: G_sub
G_sub = ____

# Add nodes from the original graph
____

# Add edges using a list comprehension with one conditional on the edge dates, that the date of the edge is earlier than 2004-05-16.
G_sub.____([(____, ____, ____) for u, v, d in G.edges(data=True) if d['____'] < ____(____,____,____)])
編輯並執行程式碼