📌 第 5 小時:資料結構(列表、字典、集合、元組)
Python 提供 四種常見的資料結構 來存放多個值:
- 列表(List):有序、可變的集合
- 字典(Dictionary):鍵值對(key-value)存放資料
- 集合(Set):無序、不重複的元素集合
- 元組(Tuple):有序、不可變的集合
這些資料結構讓 Python 更容易處理與存取資料,並適用於不同的應用場景。
🔹 1. 列表(List)
列表(List) 是一種 有序(Ordered)、可變(Mutable) 的資料結構,可以儲存不同類型的資料。
🔹 創建列表
fruits = ["apple", "banana", "cherry"]
numbers = [10, 20, 30]
mixed = ["hello", 3.14, True] # 可以存放不同類型的元素
print(fruits) # ['apple', 'banana', 'cherry']
🔹 讀取列表元素
print(fruits[0]) # apple
print(fruits[-1]) # cherry(倒數第一個)
🔹 修改列表
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry']
🔹 列表操作
操作 | 說明 | 範例 |
---|---|---|
append(x) |
在列表尾部新增元素 | fruits.append("mango") |
insert(i, x) |
在指定位置插入元素 | fruits.insert(1, "orange") |
remove(x) |
移除指定元素 | fruits.remove("apple") |
pop(i) |
移除並回傳元素(預設最後一個) | fruits.pop() |
sort() |
排序列表(預設升序) | numbers.sort() |
reverse() |
反轉列表順序 | fruits.reverse() |
🟢 範例
fruits.append("mango") # 加入 'mango'
fruits.remove("banana") # 移除 'banana'
fruits.sort() # 排序
print(fruits) # ['apple', 'cherry', 'mango']
🔹 2. 字典(Dictionary)
字典(Dictionary) 是 鍵值對(key-value) 的集合,允許快速查找資料。
🔹 創建字典
student = {
"name": "Alice",
"age": 20,
"score": 90
}
🔹 讀取字典資料
print(student["name"]) # Alice
print(student.get("age")) # 20
🔹 修改字典
student["age"] = 21 # 修改 age
student["city"] = "New York" # 新增 key-value
🔹 字典操作
操作 | 說明 | 範例 |
---|---|---|
keys() |
取得所有鍵 | student.keys() |
values() |
取得所有值 | student.values() |
items() |
取得鍵值對 | student.items() |
pop(key) |
移除並回傳值 | student.pop("age") |
🟢 範例
for key, value in student.items():
print(f"{key}: {value}")
🔹 3. 集合(Set)
集合(Set) 是 無序(Unordered)、不重複(Unique) 的元素集合。
🔹 創建集合
numbers = {1, 2, 3, 3, 4, 5}
print(numbers) # {1, 2, 3, 4, 5}(重複的 3 被自動去除)
🔹 集合操作
操作 | 說明 | 範例 |
---|---|---|
add(x) |
新增元素 | numbers.add(6) |
remove(x) |
移除元素(不存在會報錯) | numbers.remove(3) |
discard(x) |
移除元素(不存在不報錯) | numbers.discard(3) |
union(set2) |
聯集 | set1.union(set2) |
intersection(set2) |
交集 | set1.intersection(set2) |
difference(set2) |
差集 | set1.difference(set2) |
🟢 範例
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2) # {1, 2, 3, 4, 5}(聯集)
print(set1 & set2) # {3}(交集)
print(set1 - set2) # {1, 2}(差集)
🔹 4. 元組(Tuple)
元組(Tuple) 是 有序(Ordered)、不可變(Immutable) 的集合。
🔹 創建元組
coordinates = (10, 20, 30)
print(coordinates[0]) # 10
🔹 為何使用元組?
- 不可變(Immutable),防止資料被意外更改
- 比列表(List)效能更高
- 可作為字典的鍵(Dictionary Key)
🔹 不能修改元組
coordinates[0] = 100 # ❌ 會報錯,元組不可變
🔹 轉換資料結構
轉換 | 方法 |
---|---|
列表轉元組 | tuple([1, 2, 3]) |
元組轉列表 | list((1, 2, 3)) |
列表轉集合 | set([1, 2, 3]) |
🟢 範例
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple) # (1, 2, 3)
📌 第 5 小時小結
✅ 列表(List):有序、可變,可使用 append()
、remove()
✅ 字典(Dictionary):鍵值對結構,可使用 keys()
、values()
✅ 集合(Set):無序、不重複,可使用 union()
、intersection()
✅ 元組(Tuple):有序、不可變,適用於不希望被修改的資料
✅ 列表、字典、集合、元組可相互轉換
至此,你已掌握 Python 的四種基本資料結構,下一步我們將學習 物件導向程式設計(OOP)!🚀
沒有留言:
張貼留言