Python 資料結構入門(三):修改、刪除與新增 List(清單)資料
在前兩篇文章中,我們學會了如何建立清單以及取得清單中的資料
再來我們來進一步看看,有哪些絕招可以修改、刪除跟新增清單資料吧!
修改 List 中的任意元素的資料
因為 List 是 可變動的,這代表我們可以直接透過位置,直接「索引」來修改清單裡的元素。
fruits = [“apple”, “banana”, “cherry”]
fruits[1] = “orange”
調整過後 fruits 就會變成 [“apple”, “orange”, “cherry”]
新增 / 減少 List 清單內的資料
在尾端新增元素:append()
fruits = [“apple”, “orange”, “cherry”]
fruits.append(“lemon”)
調整過後 fruits 就會變成 [“apple”, “orange”, “cherry”, “lemon”]
在指定位置插入元素:insert()
fruits = [“apple”, “orange”, “cherry”, “lemon”]
fruits.insert(1, “mango”)
調整過後 fruits 就會變成 [“apple”, “mango”, “orange”, “cherry”, “lemon”]
在尾端新增多個元素:extend()
fruits = [“apple”, “mango”, “orange”, “cherry”, “lemon”]
fruits.extend([“peach”, “grape”])
調整過後 fruits 就會變成 [“apple”, “mango”, “orange”, “cherry”, “lemon”, “peach”, “grape”]
按照提供的元素指定刪除:remove(元素)
fruits = [“apple”, “mango”, “orange”, “cherry”, “lemon”, “peach”, “grape”]
fruits.remove(“cherry”)
調整過後 fruits 就會變成 [“apple”, “mango”, “orange”, “lemon”, “peach”, “grape”]
按照指定位置刪除:pop(位置)
fruits = [“apple”, “mango”, “orange”, “lemon”, “peach”, “grape”]
fruits.pop(3)
調整過後 fruits 就會變成 [“apple”, “mango”, “orange”, “peach”, “grape”]
fruits.pop()
如果不指定位置就是從尾端刪除
調整過後 fruits 就會變成 [“apple”, “mango”, “orange”, “peach”]
刪除整個 Lsit 清單內的資料:clear()
fruits = [“apple”, “mango”, “orange”, “peach”]
fruits.clear()
最後 fruits 就會變成 [] 了
Tips:append()、insert()、extend()、remove()、pop()、clear() 這些都是 List 常見絕招,只要能掌握這些絕招後,就可以讓我們能使用 List 來輕鬆處理資料啦!
stanCode標準程式教育機構-你也值得更好的教育
Facebook|https://www.facebook.com/stancode.tw
Instagram|https://www.instagram.com/stancode_tw/
YouTube|https://www.youtube.com/@stancode7228/videos
Website|https://www.stancode.tw/
TikTok|https://www.tiktok.com/@standardcoding
