Day 1 決定了這次 30 天的學習方向後,我今天正式開始接觸 Python。
原本有考慮使用電腦安裝 Python 和開發環境,但後來決定使用 Google Colab 作為這次學習的主要工具。Colab 可以直接在瀏覽器中撰寫及執行 Python,不需要另外設定複雜的開發環境,對於剛開始學習 Python 的我來說比較方便。
今天主要學習 Python 的基本資料處理方式,包括變數、資料型態、List 和 Dictionary。
一、變數與資料型態
變數可以用來儲存資料,例如:
name = "Python"
price = 450
rating = 4.8
這裡的 name、price 和 rating 分別儲存了不同的資料。
Python 常見的資料型態包括:
str:文字
int:整數
float:小數
bool:True 或 False
也可以利用 type() 查看資料的型態:
name = "Python"
price = 450
rating = 4.8
is_available = True
print(type(name))
print(type(price))
print(type(rating))
print(type(is_available))
二、List
如果需要一次儲存多筆資料,可以使用 List。
products = ["手機", "筆電", "耳機"]
print(products[0])
print(products[1])
print(products[2])
需要注意的是,Python 的索引是從 0 開始。
因此第一個資料是 products[0],第二個資料是 products[1]。
這個觀念對之後處理爬蟲取得的大量資料很重要。
三、Dictionary
Dictionary 可以使用「Key 和 Value」的方式整理一筆資料。
例如,我可以用它來表示一個商品:
product = {
"name": "無線耳機",
"price": 1990,
"rating": 4.5
}
print(product["name"])
print(product["price"])
print(product["rating"])
執行後可以取得:
無線耳機
1990
4.5
我發現 Dictionary 很適合用來整理之後爬蟲取得的資料,因為商品名稱、價格、評價等資訊都可以使用不同的 Key 儲存。
四、把 List 和 Dictionary 結合
接著我嘗試把多個商品放在一起:
products = [
{
"name": "無線耳機",
"price": 1990,
"rating": 4.5
},
{
"name": "機械鍵盤",
"price": 2500,
"rating": 4.7
},
{
"name": "滑鼠",
"price": 890,
"rating": 4.3
}
]
for product in products:
print(product["name"], product["price"], product["rating"])
結果:
無線耳機 1990 4.5
機械鍵盤 2500 4.7
滑鼠 890 4.3
這讓我開始理解之後的爬蟲資料可能會長什麼樣子。
例如:
網頁
↓
取得商品資料
↓
List + Dictionary
↓
整理資料
↓
Pandas
↓
資料分析
五、今天的實作心得
今天最大的收穫是開始理解 Python 如何儲存和整理資料。
一開始看到 List 和 Dictionary 時覺得兩者很像,但實際操作後發現,List 比較適合存放一系列資料,而 Dictionary 則很適合描述一筆具有不同欄位的資料。
尤其是把 List 和 Dictionary 結合之後,我發現這種結構和未來要處理的商品爬蟲資料很接近。
今天也第一次使用 Google Colab 實際撰寫 Python,整體操作比想像中簡單。接下來會繼續學習 Python 的流程控制,讓程式可以自動處理更多資料。