← 返回大綱
第五章

串列、元組
與字典處理

Lists, Tuples & Dictionaries

Scratch → Python

清單 → list

Scratch
清單 fruits
Python
fruits = ["蘋果", "香蕉", "芒果"]
fruits = ["蘋果", "香蕉", "芒果"]

print(fruits[0])      # 蘋果(索引從 0 開始)
print(fruits[-1])     # 芒果(-1 是最後一個)
print(fruits[0:2])    # ['蘋果', '香蕉'](切片)
print(len(fruits))    # 3(長度)
索引從 0 開始!

第一個元素是 [0],第二個是 [1],以此類推。

list 方法

清單常用方法

Scratch
將 "鳳梨" 加入 fruits
刪除 fruits 第 1 項
fruits 的項目數
Python
fruits.append("鳳梨")
fruits.pop(0)
len(fruits)
fruits.append("鳳梨")      # 加到末尾
fruits.insert(1, "葡萄")   # 插入指定位置
fruits.remove("香蕉")      # 刪除指定值
fruits.pop(0)              # 刪除並回傳指定索引的值
fruits.sort()              # 排序
fruits.reverse()           # 反轉
print("芒果" in fruits)    # True/False — 是否存在
元組

元組 tuple — 不可修改的清單

point = (3, 5)         # 用小括號建立
colors = ("red", "green", "blue")

print(point[0])        # 3
print(len(colors))     # 3

# 元組無法修改!
# point[0] = 10        # 錯誤!TypeError

list

  • [ ]
  • 可以修改(新增、刪除、更改)
  • 適合動態資料

tuple

  • ( )
  • 不可修改(唯讀)
  • 適合固定資料(座標、設定值)
字典

字典 dict — 鍵值對

用「鍵」查找「值」,就像真實的字典用單字查定義:

student = {
    "name": "Ian",
    "age": 18,
    "score": 95
}

print(student["name"])     # Ian
print(student["score"])    # 95
print(student.get("city", "未知"))  # 未知(找不到時的預設值)
dict vs list

list:用數字索引存取。
dict:用有意義的「鍵」存取,語意更清晰。

字典

字典常用操作

student = {"name": "Ian", "age": 18}

# 新增 / 修改
student["city"] = "台北"
student["age"] = 19

# 刪除
del student["city"]

# 遍歷
for key in student:
    print(key, ":", student[key])

# 更常用的方式
for key, value in student.items():
    print(f"{key}: {value}")

print(student.keys())    # dict_keys(['name', 'age'])
print(student.values())  # dict_values(['Ian', 19])
集合

集合 set — 無重複元素

nums = {1, 2, 3, 2, 1}
print(nums)          # {1, 2, 3}  自動去除重複

# 常用來去重
scores = [85, 92, 85, 78, 92, 100]
unique = set(scores)
print(unique)        # {78, 85, 92, 100}

# 集合運算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a & b)   # {3, 4}  交集
print(a | b)   # {1, 2, 3, 4, 5, 6}  聯集
print(a - b)   # {1, 2}  差集
進階

巢狀資料結構

清單裡可以放字典,字典裡可以放清單:

students = [
    {"name": "Alice", "score": 95},
    {"name": "Bob",   "score": 82},
    {"name": "Charlie", "score": 78}
]

# 取得 Bob 的分數
print(students[1]["score"])   # 82

# 找出最高分
best = max(students, key=lambda s: s["score"])
print(f"最高分:{best['name']} — {best['score']} 分")
# 最高分:Alice — 95 分
實作練習

動手試試看

# 建立一個簡單的通訊錄
contacts = {}

while True:
    action = input("輸入 add/find/quit:")
    if action == "add":
        name = input("姓名:")
        phone = input("電話:")
        contacts[name] = phone
        print("已新增!")
    elif action == "find":
        name = input("搜尋姓名:")
        if name in contacts:
            print(f"{name}:{contacts[name]}")
        else:
            print("找不到此聯絡人")
    elif action == "quit":
        break

第五章完成!

學會了 list、tuple、dict、set 四種資料結構。