Python元組(Tuple)基礎與應用
1. 元組的創建和基本操作
# 創建元組
empty_tuple = ()
single_tuple = (1,) # 注意逗號
numbers = (1, 2, 3, 4, 5)
mixed = (1, "Python", 3.14, True)
# 使用tuple()函數創建
chars = tuple("Python") # ('P', 'y', 't', 'h', 'o', 'n')
# 訪問元素
first = numbers[0] # 1
last = numbers[-1] # 5
# 切片
subset = numbers[1:4] # (2, 3, 4)
注意事項:
- 元組是不可變的(immutable)
- 單個元素的元組需要加逗號
- 元組的索引從0開始
2. 元組解包
基本解包
# 基本解包
point = (3, 4)
x, y = point
print(f"x={x}, y={y}") # x=3, y=4
# 使用*運算符處理多餘的值
first, *rest = (1, 2, 3, 4, 5)
print(first) # 1
print(rest) # [2, 3, 4, 5]
# 忽略某些值
name, _, age = ("張三", "男", 25)
print(f"{name}今年{age}歲")
3. 元組的應用場景
返回多個值
def get_user_info():
name = "張三"
age = 25
city = "台北"
return name, age, city # 自動打包為元組
# 接收返回值
name, age, city = get_user_info()
print(f"{name}住在{city},今年{age}歲")
坐標系統
def calculate_distance(point1, point2):
x1, y1 = point1
x2, y2 = point2
distance = ((x2-x1)**2 + (y2-y1)**2) ** 0.5
return distance
point1 = (0, 0)
point2 = (3, 4)
distance = calculate_distance(point1, point2)
print(f"兩點距離:{distance}")
4. 元組與列表的轉換
# 元組轉列表
tuple_data = (1, 2, 3)
list_data = list(tuple_data)
list_data.append(4) # [1, 2, 3, 4]
# 列表轉元組
list_data = [1, 2, 3, 4]
tuple_data = tuple(list_data) # (1, 2, 3, 4)
5. 練習題
-
實現學生信息管理:
- 創建包含學生信息(姓名、年齡、成績)的元組列表
- 實現按成績排序
- 計算平均成績
- 找出最高分和最低分的學生
-
坐標系統應用:
- 創建多個點的坐標元組
- 計算任意兩點間距離
- 找出距離原點最近和最遠的點
- 判斷三個點是否能形成三角形