list(列表)是 Python 最常用的容器,用方括號 [] 包住,元素可以改動、可以重複,也保持加入的順序。
先建立一個 list,再用 for 逐個讀出來。
my_list = [10, 20, 30, 40, 50]
for value in my_list:
print(value)output:
10 20 30 40 50
append() 把新元素加到結尾;prices[1] 用 index 讀第二個元素(index 由 0 開始)。
prices = [100, 102, 99]
prices.append(105) # 加到結尾
print(prices[1]) # 102(index 1)output:
102
pop(index):移除並回傳 index 位置的元素(不填就默認最後一個)。
prices = [100, 102, 99, 105]
prices.pop(2) # 移除 index 2 的 99,並回傳
print(prices) # [100, 102, 105]output:
[100, 102, 105]
remove(value):刪掉第一個值等於 value 的元素。
prices = [100, 102, 99, 105]
prices.remove(99) # 刪掉第一個 99
print(prices) # [100, 102, 105]output:
[100, 102, 105]
del prices[index]:按 index 刪元素,不回傳。
prices = [100, 102, 99]
del prices[0] # 刪掉 100
print(prices) # [102, 99]output:
[102, 99]
用 sum() 加總、len() 數數量,計平均。
race_times = [72.5, 74.2, 71.8, 73.1]
avg_time = sum(race_times) / len(race_times)
print(f"Average time: {avg_time:.1f}s") # 72.9soutput:
Average time: 72.9s
