跳至正文

串列和元組

串列 (List)

串列是有序的、可變的集合。

建立串列

# 空串列
empty = []
empty = list()

# 有值的串列
numbers = [1, 2, 3, 4, 5]
names = ["홍길동", "김철수", "이영희"]
mixed = [1, "hello", 3.14, True]

# 巢狀串列
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# 用range建立
numbers = list(range(1, 6)) # [1, 2, 3, 4, 5]
evens = list(range(0, 11, 2)) # [0, 2, 4, 6, 8, 10]

索引和切片

fruits = ["사과", "바나나", "체리", "포도", "멜론"]

# 索引
print(fruits[0]) # 사과
print(fruits[-1]) # 멜론
print(fruits[2]) # 체리

# 切片
print(fruits[1:4]) # ['바나나', '체리', '포도']
print(fruits[:3]) # ['사과', '바나나', '체리']
print(fruits[2:]) # ['체리', '포도', '멜론']
print(fruits[::2]) # ['사과', '체리', '멜론'] (每隔2個)
print(fruits[::-1]) # ['멜론', '포도', '체리', '바나나', '사과'] (反轉)

# 二維串列
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[0]) # [1, 2, 3]
print(matrix[1][2]) # 6

修改串列

fruits = ["사과", "바나나", "체리"]

# 更改元素
fruits[1] = "딸기"
print(fruits) # ['사과', '딸기', '체리']

# 更改切片
numbers = [1, 2, 3, 4, 5]
numbers[1:4] = [20, 30]
print(numbers) # [1, 20, 30, 5]

# 新增元素
fruits.append("포도") # 末尾新增
print(fruits) # ['사과', '딸기', '체리', '포도']

fruits.insert(1, "망고") # 特定位置新增
print(fruits) # ['사과', '망고', '딸기', '체리', '포도']

# 擴充串列
more_fruits = ["멜론", "수박"]
fruits.extend(more_fruits) # 新增多個元素
print(fruits)

# 刪除元素
fruits.remove("망고") # 按值刪除
print(fruits)

popped = fruits.pop() # 刪除並返回最後一個元素
print(popped) # 수박

fruits.pop(0) # 刪除特定位置
print(fruits)

del fruits[0] # 按索引刪除
print(fruits)

fruits.clear() # 清空
print(fruits) # []

串列操作

# 連接
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(combined) # [1, 2, 3, 4, 5, 6]

# 重複
repeated = [0] * 5
print(repeated) # [0, 0, 0, 0, 0]

# 長度
print(len([1, 2, 3, 4, 5])) # 5

# 成員關係
fruits = ["사과", "바나나", "체리"]
print("사과" in fruits) # True
print("포도" in fruits) # False
print("포도" not in fruits) # True

# 計數
numbers = [1, 2, 2, 3, 2, 4]
print(numbers.count(2)) # 3

# 查找索引
fruits = ["사과", "바나나", "체리", "바나나"]
print(fruits.index("바나나")) # 1 (第一次出現)

串列排序

numbers = [3, 1, 4, 1, 5, 9, 2]

# sort() - 修改原串列
numbers.sort()
print(numbers) # [1, 1, 2, 3, 4, 5, 9]

numbers.sort(reverse=True)
print(numbers) # [9, 5, 4, 3, 2, 1, 1]

# sorted() - 返回新串列
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # [1, 1, 2, 3, 4, 5, 9]
print(numbers) # [3, 1, 4, 1, 5, 9, 2] (保留原串列)

# 字串排序
words = ["banana", "apple", "cherry"]
words.sort()
print(words) # ['apple', 'banana', 'cherry']

# 反轉
numbers.reverse()
print(numbers)

# 按鍵函數排序
words = ["apple", "pie", "zoo", "a"]
words.sort(key=len) # 按長度
print(words) # ['a', 'pie', 'zoo', 'apple']

# 複雜排序
students = [
{"name": "홍길동", "score": 85},
{"name": "김철수", "score": 92},
{"name": "이영희", "score": 78}
]
students.sort(key=lambda x: x["score"], reverse=True)
print(students)

串列推導式

# 基本形式
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]

# 帶條件
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]

# if-else
numbers = [1, 2, 3, 4, 5]
result = ["짝수" if x % 2 == 0 else "홀수" for x in numbers]
print(result) # ['홀수', '짝수', '홀수', '짝수', '홀수']

# 巢狀串列
matrix = [[i*j for j in range(1, 4)] for i in range(1, 4)]
print(matrix) # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

# 展平
nested = [[1, 2], [3, 4], [5, 6]]
flat = [num for sublist in nested for num in sublist]
print(flat) # [1, 2, 3, 4, 5, 6]

# 實用範例
names = ["홍길동", "김철수", "이영희"]
upper_names = [name.upper() for name in names]
print(upper_names)

# 條件轉換
scores = [85, 92, 78, 95, 88]
grades = ["Pass" if score >= 80 else "Fail" for score in scores]
print(grades)

元組 (Tuple)

元組是有序的、不可變的集合。

建立元組

# 空元組
empty = ()
empty = tuple()

# 有值的元組
numbers = (1, 2, 3, 4, 5)
mixed = (1, "hello", 3.14, True)

# 不用括號也可以
point = 10, 20
print(point) # (10, 20)

# 單元素元組(逗號必需!)
single = (5,)
not_tuple = (5) # 這只是一個int
print(type(single)) # <class 'tuple'>
print(type(not_tuple)) # <class 'int'>

# 從串列轉換
numbers_list = [1, 2, 3]
numbers_tuple = tuple(numbers_list)
print(numbers_tuple) # (1, 2, 3)

存取元組

colors = ("빨강", "초록", "파랑", "노랑")

# 索引
print(colors[0]) # 빨강
print(colors[-1]) # 노랑

# 切片
print(colors[1:3]) # ('초록', '파랑')

# 長度
print(len(colors)) # 4

# 成員關係
print("빨강" in colors) # True

# 計數和索引
numbers = (1, 2, 2, 3, 2)
print(numbers.count(2)) # 3
print(numbers.index(3)) # 3

元組操作

# 連接
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined = tuple1 + tuple2
print(combined) # (1, 2, 3, 4, 5, 6)

# 重複
repeated = (0,) * 5
print(repeated) # (0, 0, 0, 0, 0)

# 比較
print((1, 2) < (1, 3)) # True (字典序)
print((1, 2) == (1, 2)) # True

元組解包

# 基本解包
point = (10, 20)
x, y = point
print(x, y) # 10 20

# 多個返回值
def get_user():
return "홍길동", 25, "서울"

name, age, city = get_user()
print(name, age, city)

# 擴充解包 (Python 3+)
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
print(first) # 1
print(middle) # [2, 3, 4]
print(last) # 5

# 交換值
a, b = 1, 2
a, b = b, a
print(a, b) # 2 1

# 忽略值
point = (10, 20, 30)
x, _, z = point
print(x, z) # 10 30

元組 vs 串列

# 串列:可變
fruits_list = ["사과", "바나나"]
fruits_list.append("체리") # ✅
print(fruits_list)

# 元組:不可變
fruits_tuple = ("사과", "바나나")
# fruits_tuple.append("체리") # ❌ AttributeError

# 元組更快、更節省記憶體
import sys
list_data = [1, 2, 3, 4, 5]
tuple_data = (1, 2, 3, 4, 5)
print(sys.getsizeof(list_data)) # 104
print(sys.getsizeof(tuple_data)) # 88

# 元組可以用作字典鍵
locations = {
(0, 0): "원점",
(1, 0): "동쪽",
(0, 1): "북쪽"
}
print(locations[(0, 0)]) # 원점

# 串列不可以
# locations = {[0, 0]: "원점"} # ❌ TypeError

實務範例

學生成績管理

# 學生資訊(元組用於不可變資料)
students = [
("홍길동", 85, 90, 88),
("김철수", 92, 88, 95),
("이영희", 78, 85, 82)
]

# 計算平均分
def calculate_average(scores):
name, *grades = scores
avg = sum(grades) / len(grades)
return name, avg

for student in students:
name, avg = calculate_average(student)
print(f"{name}: 平均 {avg:.1f}分")

# 最高分學生
best_student = max(students, key=lambda x: sum(x[1:]))
print(f"最高分: {best_student[0]}")

待辦事項列表

class TodoList:
def __init__(self):
self.tasks = []

def add(self, task):
"""新增任務"""
self.tasks.append({"task": task, "done": False})
print(f"已新增 '{task}'")

def complete(self, index):
"""完成任務"""
if 0 <= index < len(self.tasks):
self.tasks[index]["done"] = True
print(f"'{self.tasks[index]['task']}' 已完成!")

def remove(self, index):
"""刪除任務"""
if 0 <= index < len(self.tasks):
task = self.tasks.pop(index)
print(f"已刪除 '{task['task']}'")

def show(self):
"""顯示任務列表"""
if not self.tasks:
print("沒有任務!")
return

print("\n=== 待辦事項列表 ===")
for i, item in enumerate(self.tasks):
status = "✓" if item["done"] else " "
print(f"{i+1}. [{status}] {item['task']}")

# 使用範例
todo = TodoList()
todo.add("Python 공부하기")
todo.add("운동하기")
todo.add("책 읽기")
todo.show()
todo.complete(0)
todo.show()

資料分析

# 銷售資料(產品名、數量、價格)
sales = [
("노트북", 5, 1200000),
("마우스", 30, 25000),
("키보드", 15, 85000),
("모니터", 8, 350000)
]

# 計算總收入
def calculate_revenue(sales_data):
total = 0
for product, quantity, price in sales_data:
revenue = quantity * price
total += revenue
print(f"{product}: {revenue:,}원")
return total

print("\n=== 產品收入 ===")
total_revenue = calculate_revenue(sales)
print(f"\n總收入: {total_revenue:,}원")

# 最暢銷產品
best_seller = max(sales, key=lambda x: x[1])
print(f"\n最暢銷: {best_seller[0]} ({best_seller[1]}개)")

# 按收入排序
sorted_sales = sorted(sales, key=lambda x: x[1] * x[2], reverse=True)
print("\n=== 收入排名 ===")
for rank, (product, qty, price) in enumerate(sorted_sales, 1):
print(f"{rank}. {product}: {qty * price:,}원")

座標管理

# 2D座標
points = [(0, 0), (3, 4), (1, 1), (5, 12)]

# 計算離原點的距離
def distance_from_origin(point):
x, y = point
return (x**2 + y**2) ** 0.5

# 計算並排序距離
distances = [(point, distance_from_origin(point)) for point in points]
distances.sort(key=lambda x: x[1])

print("=== 離原點的距離 ===")
for point, dist in distances:
print(f"{point}: {dist:.2f}")

# 最遠的點
farthest = max(points, key=distance_from_origin)
print(f"\n最遠的點: {farthest}")

常見問題

Q1. 什麼時候使用串列,什麼時候使用元組?

A: 根據是否需要修改來決定

# 串列:可變資料
shopping_cart = ["사과", "바나나"]
shopping_cart.append("우유") # 購物車經常變化

# 元組:不可變資料
birth_date = (1990, 5, 15) # 出生日期是固定的
coordinates = (37.5665, 126.9780) # 座標是固定的

Q2. 如何複製串列?

A: 區分淺拷貝和深拷貝

original = [1, 2, 3]

# 參照拷貝(相同物件)
ref = original
ref.append(4)
print(original) # [1, 2, 3, 4] - 原串列也被修改了!

# 淺拷貝(新物件)
shallow = original.copy()
# 或
shallow = original[:]
# 或
shallow = list(original)

shallow.append(5)
print(original) # [1, 2, 3, 4] - 保留原串列

# 深拷貝(巢狀串列)
import copy
nested = [[1, 2], [3, 4]]
deep = copy.deepcopy(nested)
deep[0].append(3)
print(nested) # [[1, 2], [3, 4]] - 保留原串列

Q3. 如何檢查串列是否為空?

A: 有幾種方法

my_list = []

# 方法1:檢查長度
if len(my_list) == 0:
print("為空")

# 方法2:布林轉換(Pythonic!)
if not my_list:
print("為空")

# 方法3:比較
if my_list == []:
print("為空")

Q4. 初始化多維串列時要注意什麼?

A: 小心參照拷貝

# ❌ 錯誤方法
matrix = [[0] * 3] * 3
matrix[0][0] = 1
print(matrix) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]] - 所有列都相同!

# ✅ 正確方法
matrix = [[0] * 3 for _ in range(3)]
matrix[0][0] = 1
print(matrix) # [[1, 0, 0], [0, 0, 0], [0, 0, 0]] - 正常

下一步

您已經掌握了串列和元組!

總結:
✅ 串列:可變、多種方法
✅ 元組:不可變、快速安全
✅ 索引、切片、解包
✅ 串列推導式
✅ 實務應用範例

下一步: 在字典和集合中學習更多集合!