Python 資料結構入門(四):List(清單) 的的排序、統計與查找工具
前幾篇文章中,已經知道如何建立清單、存取資料,也講了幾種方法讓我們可以新增、刪除或修改 List 裡面的內容。
第四篇,我們來解鎖一些更進階更實用的工具吧!這些工具可以幫我們更快處理資料!
排序清單:sort()
sort 可以幫我們把 List 裡面的資料 從小到大排序
numbers = [3, 1, 4, 1, 5, 9]
numbers.sort()
sort 後 numbers 就會變成 [1, 1, 3, 4, 5, 9]
反轉清單順序:reverse()
fruits = [“apple”, “orange”, “cherry”, “lemon”]
fruits.reverse()
reverse 後 fruits 就會變成 [“lemon”, “cherry”, “orange”, “apple”]
判斷元素有沒有在 List 中:in
fruits = [“lemon”, “cherry”, “orange”, “apple”]
詢問 “lemon” in fruits 因為有在 List 中,所以會是 True
詢問 “mango” in fruits 因為沒有在 List 中,所以會是 False
就可以透過這個方法來搭配 if/else 判別。
if “lemon” in fruits:
print(“We have Lemon!”)
詢問清單長度(數量):len()
fruits = [“lemon”, “cherry”, “orange”, “apple”]
想知道裡面有幾種水果,就可以使用 len(fruits),就可以知道是 4 囉!
詢問這個元素在 List 裡面出現幾次:count()
numbers = [3, 1, 4, 1, 5, 9]
想知道 numbers 裡面有幾個 1,就可以使用 numbers.count(1) 來確認~
Tips:sort()、reverse() 都是直接改變 List 的排序,count()、len()、in 會 return 一個結果(數字或boolean)
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
