## 資料結構 ### 資料結構的靈活性 在 Python 中,資料結構如字典(`dict`)和串列(`list`)可以靈活地包含其他的字典或串列,甚至可以嵌套函式,這使得資料的表達方式非常多樣化。 ### 串列中的串列(二維串列) ```python= grid = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] ``` 讀取二維串列資料 ```python=6 print(grid[1]) #印出 [4, 5, 6] print(grid[1][1]) #印出 5 ``` 用兩層迴圈遍尋所有資料 ```python=6 for y in range(3): for x in range(3): print(grid[y][x]) ``` ### 字典中的字典 ```python= pokemons = { '#0001': { 'name': '妙蛙種子', 'weight': 6.9, 'height': 0.7 }, '#0002': { 'name': '妙蛙草', 'weight': 13.0, 'height': 1.0 }, '#0003': { 'name': '妙蛙花', 'weight': 100.0, 'height': 2.0 } } ``` 讀取資料 ```python=6 print(pokemons['#0002']) #印出 { 'name': '妙蛙草', 'weight': 13.0, 'height': 1.0 } print(pokemons['#0002']['name']) #印出「妙蛙草」 ``` ### 串列中的字典 ```python= users = [ {'name': 'Chia', 'age': 18}, {'name': 'Tony', 'age': 26}, {'name': 'Debbie', 'age': 18}, {'name': 'Poyi', 'age': 13}, {'name': 'Vivian', 'age': 16} ] ``` 計算年齡的平均值 ```python=8 total = sum(d['age'] for d in users) avg = total / len(data) print(avg) # 輸出平均年齡 ``` ### 字典中的串列 ```python store = { 'name': '托尼', 'age': 18, 'scores': [99, 85, 93, 64, 79] } # 計算分數的平均值 total = sum(user['scores']) avg = total / len(user['scores']) print(avg) # 輸出托尼的平均分數 ``` ### 更複雜的結構 在實際應用中,資料結構可能會更為複雜,例如: ```python data = [ { 'name': 'Alice', 'age': 30, 'hobbies': ['reading', 'hiking'], 'scores': { 'math': 95, 'science': 89 } }, { 'name': 'Bob', 'age': 24, 'hobbies': ['gaming', 'cooking'], 'scores': { 'math': 78, 'science': 82 } } ] ``` ## JSON 格式資料 SON(JavaScript Object Notation)是一種輕量級的資料交換格式,易於人閱讀和撰寫,同時也易於機器解析和生成。它的結構與 Python 的字典和串列相似,通常用於傳輸資料,尤其是在 Web 應用中。 ## 挑戰題 - 分析寶可夢數據 底下網址是一個寶可夢的 JSON 格式資料: 寶可夢數據 [https://raw.githubusercontent.com/Purukitto/pokemon-data.json/refs/heads/master/pokedex.json](https://raw.githubusercontent.com/Purukitto/pokemon-data.json/refs/heads/master/pokedex.json) 請使用 Python 程式進行分析,完成以下任務: 1. 計算資料中總共有多少種寶可夢。 2. 使用迴圈搜尋「皮卡丘」並顯示其資料。 3. 找出攻擊力 `Attack` 最高的寶可夢。 您可以使用 `requests` 套件透過網址將 JSON 資料載入程式。以下是載入資料的範例程式碼: ```python import requests import json url = "https://raw.githubusercontent.com/Purukitto/pokemon-data.json/refs/heads/master/pokedex.json" response = requests.get(url) data = response.json() # 輸出資料以確認成功載入 print(data) ``` 另外,您也可以下載資料並將其存成 `pokemon.json` 檔案,然後使用以下程式碼將其讀入: ```python import json # 讀取本地 JSON 檔案 with open('./pokemon.json', 'r') as f: data = json.load(f) # 輸出資料以確認成功載入 print(data) ``` 完成後,您可以根據上述任務要求進行分析!