iT邦幫忙

2025 iThome 鐵人賽

DAY 14
0
Software Development

學會 Python 不可怕:我每天學一點的 30 天筆記系列 第 14

Day14 : 基礎練習 – 列表、字典、集合

  • 分享至 

  • xImage
  •  

練習1:處理水果清單 (list)
題目
https://ithelp.ithome.com.tw/upload/images/20250928/201788724XikhCgI5n.png
程式範例
https://ithelp.ithome.com.tw/upload/images/20250928/2017887291r1XhfLMG.png
輸出結果
https://ithelp.ithome.com.tw/upload/images/20250928/20178872OW6PzceRWf.png

  • append() 會把元素加到列表最後一個位置
  • insert(索引, 元素) 可以把元素插入到指定位置

練習2:學生成績表 (dict)
題目
https://ithelp.ithome.com.tw/upload/images/20250928/20178872ajuhSKA7nd.png
程式範例
https://ithelp.ithome.com.tw/upload/images/20250928/20178872EQ1F82vBor.png
輸出結果
https://ithelp.ithome.com.tw/upload/images/20250928/20178872l2pWfz71E1.png

  • grades["David"] = 77,如果 key 不存在,那麼字典就會新增一個 key-value 配對
  • grades["Alice"] = 95,如果 key 已經存在,這樣寫的話,就會修改它原本的值
  • .items() 會一次取出 key 和 value,適合用在迴圈

練習3:集合操作 (set)
題目
https://ithelp.ithome.com.tw/upload/images/20250928/20178872jXIic80X7n.png
程式範例
https://ithelp.ithome.com.tw/upload/images/20250928/20178872EDCw2qSqSd.png
輸出結果
https://ithelp.ithome.com.tw/upload/images/20250928/20178872wpgh7QvPRl.png

  • | 是聯集運算符,會把 A 和 B 的所有元素合併,但不會重複
  • & 是交集運算符,會找出 A 和 B 共同擁有的元素
  • – 是差集運算符,會找出只存在於 A,沒有出現在 B 的元素

練習題4:從 grades 字典中找出分數最高的學生名字和分數
題目
https://ithelp.ithome.com.tw/upload/images/20250928/20178872CwDZ3W0GtI.png
程式範例
https://ithelp.ithome.com.tw/upload/images/20250928/20178872WobJn3MAXb.png
輸出結果
https://ithelp.ithome.com.tw/upload/images/20250928/20178872b7I4uY453G.png

  • 首先用 top_student 先建一個空字串,等一下再放最高分學生的名字
  • top_score 先設為 0,遇到更高分再更新
  • 用 for 迴圈遍歷字典,.items() 可以一次取出 name(key)和 score(value)

上一篇
Day13 : 集合(set)基礎與應用
下一篇
Day15 : 進階挑戰 – 列表、字典、集合大練功 !
系列文
學會 Python 不可怕:我每天學一點的 30 天筆記18
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言