第3課:數據結構
課程目標
- 掌握Python的基本數據結構:列表、元組、字典、集合
- 學習字符串的高級操作方法
- 理解不同數據結構的特點和適用場景
1. 列表(List)
1.1 列表的創建和基本操作
# 創建列表
fruits = ["蘋果", "香蕉", "橙子"]
numbers = [1, 2, 3, 4, 5]# 列表索引(從0開始)
print(fruits[0]) # 蘋果
print(fruits[-1]) # 橙子(最后一個元素)# 列表切片
print(fruits[1:3]) # ['香蕉', '橙子']
print(fruits[:2]) # ['蘋果', '香蕉']
1.2 列表的常用方法
fruits = ["蘋果", "香蕉", "橙子"]# 添加元素
fruits.append("葡萄") # 在末尾添加
fruits.insert(1, "梨子") # 在指定位置插入# 刪除元素
removed = fruits.pop() # 刪除并返回最后一個元素
fruits.remove("香蕉") # 刪除指定元素# 排序
fruits.sort() # 升序排序
fruits.reverse() # 反轉列表
2. 元組(Tuple)
2.1 元組的特點和創建
# 元組是不可變的列表
coordinates = (10, 20)
person = ("張三", 25, "北京")# 元組解包
x, y = coordinates
name, age, city = person
print(f"{name}今年{age}歲,住在{city}")
3. 字典(Dictionary)
3.1 字典的創建和基本操作
# 創建字典
student = {"name": "張三","age": 20,"grades": [85, 90, 88]
}# 訪問元素
print(student["name"]) # 張三
print(student.get("age")) # 20# 添加和修改元素
student["phone"] = "13800138000"
student["age"] = 21
4. 集合(Set)
4.1 集合的特點和創建
# 集合是無序、不重復的元素集合
fruits_set = {"蘋果", "香蕉", "橙子", "蘋果"}
numbers_set = {1, 2, 3, 4, 5}# 集合運算
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}union = set1 | set2 # 并集
intersection = set1 & set2 # 交集
difference = set1 - set2 # 差集
5. 字符串的高級操作
5.1 字符串方法
text = " Hello, World! "# 大小寫轉換
print(text.upper()) # " HELLO, WORLD! "
print(text.lower()) # " hello, world! "# 去除空白
print(text.strip()) # "Hello, World!"# 查找和替換
print(text.find("World")) # 8
print(text.replace("World", "Python"))
6. 練習項目
項目:學生成績管理系統
print("=== 學生成績管理系統 ===")students = {}while True:print("\n請選擇操作:")print("1. 添加學生")print("2. 錄入成績")print("3. 查詢成績")print("4. 退出")choice = input("請輸入選擇(1-4):")if choice == "1":student_id = input("請輸入學號:")name = input("請輸入姓名:")age = int(input("請輸入年齡:"))students[student_id] = {"name": name,"age": age,"grades": {}}print("學生添加成功!")elif choice == "2":student_id = input("請輸入學號:")if student_id in students:subject = input("請輸入科目:")score = float(input("請輸入成績:"))students[student_id]["grades"][subject] = scoreprint("成績錄入成功!")else:print("學號不存在!")elif choice == "3":student_id = input("請輸入學號:")if student_id in students:student = students[student_id]print(f"\n學生信息:{student['name']},年齡:{student['age']}")if student['grades']:print("成績:")for subject, score in student['grades'].items():print(f" {subject}: {score}")else:print("暫無成績記錄")else:print("學號不存在!")elif choice == "4":print("感謝使用!")breakelse:print("無效選擇,請重新輸入!")
7. 總結
本節課我們學習了:
- 列表的創建、操作和常用方法
- 元組的特點和不可變性
- 字典的鍵值對結構和操作
- 集合的無序性和去重特性
- 字符串的高級操作方法
8. 下節課預告
下節課我們將學習:
- 函數的定義和調用
- 參數傳遞和返回值
- 作用域和命名空間