第 4 章 · 数据结构
本章目标:掌握 列表 list、元组 tuple、字典 dict、集合 set 的创建与常用操作;理解可变与不可变;熟练使用切片、推导式与 sorted();能用字典组织 shop-demo 商品目录与 user-demo 订单项。
学时建议:4~5 小时(含 1.5 小时跟练)
前置:ch02~ch03 变量与流程控制。
4.1 列表 list
有序、可变、可重复。
books = ["Python 基础", "Web 入门", "数据分析"]
books.append("自动化脚本")
books[0] = "Python 3 基础"
print(len(books)) # 4
print(books[-1]) # 最后一项
| 方法 | 作用 |
|---|---|
append(x) | 末尾添加 |
insert(i, x) | 指定位置插入 |
pop() / pop(i) | 弹出并返回 |
remove(x) | 删除首个匹配值 |
extend(iterable) | 合并列表 |
sort() / sorted() | 原地排序 / 返回新列表 |
reverse() | 原地反转 |
prices = [29.9, 19.5, 49.0]
prices.sort()
print(sorted(prices, reverse=True))
内置sort/sorted底层为 Timsort(归并+插入混合)。经典算法原理与场景选型见 ch16。
切片
nums = [0, 1, 2, 3, 4, 5]
nums[1:4] # [1, 2, 3]
nums[:3] # [0, 1, 2]
nums[::2] # [0, 2, 4]
nums[::-1] # 反转副本
切片得到新列表(浅拷贝)。
4.2 元组 tuple
有序、不可变,可作字典键。
point = (10, 20)
rgb = 255, 128, 0 # 括号可省略
x, y = point # 解包
# 单元素元组必须有逗号
t = (42,)
| list vs tuple | list | tuple |
|---|---|---|
| 可变性 | 可变 | 不可变 |
| 性能 | 略慢 | 略快 |
| 典型用途 | 动态集合 | 固定记录、函数多返回值 |
def min_max(nums):
return min(nums), max(nums)
low, high = min_max([3, 1, 4])
4.3 字典 dict
键值映射,键须可哈希(通常 str、int、tuple)。
product = {
"sku": "BK-001",
"title": "Python 入门",
"price": 59.9,
"stock": 12,
}
product["stock"] -= 1
product["category"] = "技术"
print(product.get("author", "佚名"))
print("price" in product) # True
| 方法 | 说明 |
|---|---|
keys() / values() / items() | 遍历 |
get(k, default) | 安全取值 |
pop(k) | 删除并返回 |
update(other) | 合并 |
dict.fromkeys(keys, v) | 批量建键 |
for sku, item in catalog.items():
print(sku, item["title"], item["price"])
嵌套结构
order = {
"order_id": "ORD-1001",
"user": "user-demo",
"lines": [
{"sku": "BK-001", "qty": 2, "price": 59.9},
{"sku": "BK-002", "qty": 1, "price": 39.0},
],
}
4.4 集合 set
无序、不重复,支持交并差。
tags_a = {"python", "web", "data"}
tags_b = {"python", "ml", "data"}
print(tags_a | tags_b) # 并集
print(tags_a & tags_b) # 交集
print(tags_a - tags_b) # 差集
seen = set()
for sku in ["A", "B", "A", "C"]:
seen.add(sku)
print(seen) # {'A', 'B', 'C'}
| 场景 | 用法 |
|---|---|
| 去重 | list(set(lst))(顺序可能变) |
| 成员检测 | x in big_set 平均 O(1) |