想像一下,你要存放 5 個學生的分數。
用單一變數:
score1 = 80
score2 = 92
score3 = 75
score4 = 88
score5 = 90
太麻煩了!如果學生有 1000 個呢?
這時候,需要一次性存放一組資料的工具:陣列(Array)或清單(List)。
陣列/清單是一個有序的集合,可以用索引(index)來存取。
索引從 0 開始,每個元素(element)都可以快速讀取或修改。
範例
scores = [80, 92, 75, 88, 90]
#存取元素
print(scores[0]) # 80
print(scores[3]) # 88
#修改元素
scores[2] = 77
print(scores) # [80, 92, 77, 88, 90]
#新增元素
scores.append(95)
print(scores) # [80, 92, 77, 88, 90, 95]
搭配迴圈使用
陣列的強大之處在於,它能搭配迴圈一次處理所有資料。
scores = [80, 92, 77, 88, 90]
for s in scores:
print("分數:", s)
這樣就不用一個一個輸出,程式更簡潔。
學會了如何用陣列/清單來處理一群資料,這是程式邁向資料處理的重要一步。
明天,我們將進一步探索字典(Dictionary)與物件(Object),學會如何處理有意義的資料配對。