開始使用免費開始

撰寫產生器以分批載入資料(3)

太好了!你剛剛建立了一個產生器函式,之後可以用它來處理大型檔案。

現在,讓我們用你的產生器函式來處理世界銀行的資料集,就像你先前做過的一樣。你會逐行讀取檔案,建立一個字典來計數資料集中某一欄位裡每個國家出現的次數。不過這次不只處理 1000 列,而是要處理整個資料集!

產生器函式 read_large_file() 和 CSV 檔案 'worlddevind.csv' 已經預先載入並可直接使用。開始動手吧!

本練習屬於課程

Python 工具箱

檢視課程

練習說明

  • 在情境管理器中使用 open(),將檔案 'worlddevind.csv' 綁定到 file
  • 完成 for 迴圈,讓它疊代呼叫 read_large_file() 所回傳的產生器,以處理檔案中的所有列。

動手互動練習

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

# Initialize an empty dictionary: counts_dict
counts_dict = {}

# Open a connection to the file
with ____ as ____:

    # Iterate over the generator from read_large_file()
    for line in ____:

        row = line.split(',')
        first_col = row[0]

        if first_col in counts_dict.keys():
            counts_dict[first_col] += 1
        else:
            counts_dict[first_col] = 1

# Print            
print(counts_dict)
編輯並執行程式碼